Tcs Coding Questions 2021 Info

Example N=4:

1
2 3
4 5 6
7 8 9 10

Concept: Counter variable inside nested loops.

TCS coding questions often come with hidden constraints that are not explicitly stated in the problem text but are crucial for passing all test cases.


for i in range(n-1, mid-1, -1): print(arr[i], end=" ")


Asked in: TCS Digital (April 2021)

Problem Statement:
Given an array of integers (positive and negative), find the second smallest element and the second largest element without using any sorting algorithm or inbuilt sorting functions. Tcs Coding Questions 2021

Constraints: Time Complexity O(N), Space Complexity O(1).

Example:

Approach (C++):

#include <iostream>
#include <climits>
using namespace std;

int main() int arr[] = 12, 35, 1, 10, 34, 1; int n = sizeof(arr)/sizeof(arr[0]);

int first_large = INT_MIN, second_large = INT_MIN;
int first_small = INT_MAX, second_small = INT_MAX;
for(int i = 0; i < n; i++) 
    // For largest
    if(arr[i] > first_large) 
        second_large = first_large;
        first_large = arr[i];
     else if(arr[i] > second_large && arr[i] != first_large) 
        second_large = arr[i];
// For smallest
    if(arr[i] < first_small) 
        second_small = first_small;
        first_small = arr[i];
     else if(arr[i] < second_small && arr[i] != first_small) 
        second_small = arr[i];
cout << "Second Largest: " << second_large << endl;
cout << "Second Smallest: " << second_small << endl;
return 0;

Difficulty: Medium
Marks: 15

Statement:
Given an array of N integers and an integer K, find the number of unique pairs (i, j) with i < j such that arr[i] + arr[j] = K.

Example:
Input: arr = [1, 5, 7, 1, 5], K = 6
Pairs: (1,5) at indices (0,1) and (0,3), but unique values?
Here values (1,5) is one pair. So answer = 1.

Wait – clarify:
Better example: arr = [1, 2, 3, 4, 3], K = 6
Pairs: (2,4) and (3,3) → 2 pairs. Example N=4: 1 2 3 4 5 6 7 8 9 10

Constraints:
1 ≤ N ≤ 10⁵
-10⁹ ≤ arr[i], K ≤ 10⁹

Input format:
First line: N K
Second line: N integers.

Output format:
Integer count.

Sample Input:
5 6
1 2 3 4 3

Sample Output:
2