You may recognise an array or string problem and still lose time because you cannot decide what state the loop should store. Four shapes of state answer most of the coding work you meet in a TCS drive: a current run, the best two values seen so far, a frequency table, and one total with a running left sum. Choose the wrong one and you write the quadratic version that clears the sample case and times out on the hidden tests.
TCS coding questions: what stays the same when the format changes
In the TCS NQT the coding work sits with Programming Logic, and the Ninja, Digital and Prime tracks all draw on the same small set of loop shapes: direct simulation, one-pass array state, frequency counting, and prefix-sum reasoning. Confirm the current assessment, allowed languages, section rules, eligibility, and hiring process on the official TCS iON NQT page. The TCS NQT Preparation: Exam Pattern, Sections and a Study Plan sets out how that section sits beside the aptitude papers and how to split your weeks.
Before coding, write a four-line contract:
input:[4, 1, 9, 9, 7, 4]required output: second-largest distinct valueconstraints: duplicates do not create a rankedge cases: return not found if fewer than two distinct values exist
That word distinct prevents the incorrect answer 9.
Choose the pattern from the input and output clues
Problem clue | State to maintain | Representative task | Target complexity |
|---|---|---|---|
Consecutive equal items | Current character and run length | Encode |
|
Best two values under duplicate rules | Largest and second largest | Process |
|
Property based on total occurrence count | Frequency map and second scan | First non-repeating character of |
|
Left sum compared with right sum | Total and running left sum | Equilibrium index of |
|
The output wording selects the state. Distinct changes the update rule, first requires original order, and left equals right suggests one total instead of repeated sums. For digit logic, GCD and prime checks, series and factorial problems, and the same solutions written out in both Python and Java, see TCS NQT Coding Questions 2026: Pattern-Wise Solutions in Python and Java.
Solved pattern 1: direct simulation with run-length encoding
Define runLengthEncode(s) for a non-null string. Replace every maximal consecutive run with its character followed by its count. For aaabbccccd, the result is a3b2c4d1. If empty input is allowed, return an empty string.
Start with current='a' and count=1. The next two a characters increase the count to 3. At the first b, append a3, then set current='b' and count=1. The second b raises it to 2. At c, append b2; four c characters finish at 4. At d, append c4, then set the state to d,1. After the loop, flush the final run to obtain a3b2c4d1. Forgetting this flush loses d1.
def run_length_encode(s):
if not s:
return ""
parts = []
current, count = s[0], 1
for char in s[1:]:
if char == current:
count += 1
else:
parts.append(f"{current}{count}")
current, count = char, 1
parts.append(f"{current}{count}")
return "".join(parts)The scan takes O(n) time, and the output takes O(n) space. Appending tokens to a list and joining once avoids repeated copying of an immutable string. Check "q" -> "q1", "zzzz" -> "z4", and "" -> "".
Solved pattern 2: second-largest distinct value in one pass
For secondLargestDistinct(values), input [4, 1, 9, 9, 7, 4] must return 7. Keep nullable states largest and second, not a numeric sentinel that could fail on negative input. For each x, if largest is empty or x > largest, move the old largest to second and store x in largest. Otherwise, if x != largest and second is empty or x > second, store x in second.
The dry run is:
4 -> (4, none)1 -> (4, 1)9 -> (9, 4)duplicate
9 -> (9, 4)7 -> (9, 7)final
4 -> (9, 7)
Return 7. Sorting is unnecessary when only two ranks matter. This method takes O(n) time and O(1) extra space. Its failure contract is [5, 5] -> not found, not 5. The test [-4, -1, -3] -> -3 confirms that the implementation neither assumes zero nor relies on an unsafe fixed sentinel.
![Dry-run table for secondLargestDistinct([4, 1, 9, 9, 7, 4]) tracking largest and second at each value to the final answer 7.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784572355863_gfzld0.jpg)
Solved pattern 3: frequency map plus an order-preserving scan
Define firstNonRepeating(s) for lowercase English letters. For swiss, the answer is w.
In the first pass, count every character: s:3, w:1, and i:1. In the second pass, follow the original order s, w, i, s, s. Skip s because its count is 3, then stop at w because its count is 1.
The task asks for the first qualifying character, not any key with count one. A second scan preserves original order without relying on language-specific map iteration. The two passes take O(n) time and O(k) extra space, where k is the number of distinct characters. Under the lowercase-English contract, an array of 26 counts also uses O(1) alphabet space.
Test "aabb" -> not found and "x" -> "x". Treat "aAb" as a contract violation unless case handling is defined first. Silently converting it to lowercase would change the input semantics.
Solved pattern 4: equilibrium index with one total sum
Define zero-based equilibriumIndex(values) to return the first index where the sum strictly to its left equals the sum strictly to its right, or -1 if no such index exists. For [1, 3, 5, 2, 2], the total is 13.
Start with left=0. At each index, compute right = total - left - current:
Index | Value | Left | Right |
|---|---|---|---|
0 | 1 | 0 | 12 |
1 | 3 | 1 | 9 |
2 | 5 | 4 | 4 |
3 | 2 | 9 | 2 |
4 | 2 | 11 | 0 |
At index 2, both sides equal 4, so return 2 immediately. The final two rows show what the state would be if the scan continued. Recomputing both sides at every position can take O(n^2) time. One total and a running left sum reduce this to O(n) time and O(1) extra space.
Check [2, 1, -1] -> 0, because the empty left side and 1 + (-1) both sum to zero. Also check [7] -> 0 when a single element is allowed, and [1, 2, 3] -> -1.
![Index diagram for the array [1, 3, 5, 2, 2] showing left and right sums per position, with index 2 balanced where both sides equal 4.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784572356491_fwfn23.jpg)
Test the contract before trusting the sample output
Function | Normal case | Edge case | Bug exposed |
|---|---|---|---|
Run-length encoding |
|
| Missing final flush |
Second-largest distinct |
|
| Ranking a duplicate |
First non-repeating |
|
| Returning any minimum-frequency key |
Equilibrium index |
|
| Mishandling an empty side or negative values |
Before submission, parse the documented input shape, reset state between test cases, remove debug output, choose integer width from the stated constraints, and define empty or invalid input. Do not guess platform limits. Use Coding Round Strategy: How to Clear Online Coding Tests in Placements for a wider constraints, dry-run, edge-case, and time-allocation routine.
The short version: a repeatable TCS practice loop
For each problem, classify the clue, write the brute-force version, name the smaller state, dry-run one normal case, then test a duplicate, empty, negative, or no-answer case where relevant. Next time, change the values: xxxyzz -> x3y1z2; [8, 2, 8, 6] -> 6; level -> v; and [0, 0] -> 0 under the empty-side-sum rule.
The TCS category collects the rest of the TCS preparation material, and the TCS Test Series puts the same kind of problems in front of you under a clock. Practise the state changes until you can explain each one before writing code.




