Tech Mahindra Coding Questions: 4 Patterns with Solved Examples

Stop memorising finished programs. Learn to recognise frequency counting, two pointers, sliding windows and run-length tracking, then dry-run each method.

KnowledgeGate Team

Exam prep & CS education

Updated 4 Nov 20266 min read136 views
Tech Mahindra Coding Questions: 4 Patterns with Solved Examples

Many candidates can solve a familiar program after seeing its answer, but freeze when a coding round changes the values or wraps the same logic in a new story. The missing skill is pattern recognition, not another memorised solution. These four illustrative Tech Mahindra preparation problems teach reusable methods through exact dry runs, complexity analysis and boundary checks. They are not an official question list, so use your current invitation for live process details and use Placement Preparation & Coding to organise practice.

Three earlier same-node guides own narrower worked sets: Wipro Coding Questions: 3 Solved Patterns with Step-by-Step Traces keeps its swiss first-unique and fixed-window examples; HCLTech Coding Questions: Solve 4 Core Patterns Step by Step owns complement-map, bracket and greedy traces; and TCS Coding Questions: 4 Patterns with Solved Dry Runs owns its aaabbccccd run-length and equilibrium examples. This post keeps the transfer drill on sorted pair-sum, unique-window boundary movement and the final-run flush.

Read the prompt as a pattern signal, not a story

Certain words tell you which state to maintain.

Prompt signal

Likely pattern

Count, duplicate, first unique or anagram

Frequency table, then an ordered pass if position matters

Sorted array, pair and target

Two pointers

Longest or shortest contiguous segment

Sliding window

Consecutive repeated characters

Run-length tracking with a final flush

Check constraints before coding. For a teaching input with n = 100,000, nested pair search can make n(n-1)/2 = 100,000 x 99,999 / 2 = 4,999,950,000 comparisons. After sorting, a two-pointer scan makes at most n-1 = 99,999 pointer moves. These are teaching values, not Tech Mahindra limits.

Use one answer frame: define the state and invariant, dry-run the values, give time and auxiliary space, then test the smallest input, duplicates and a no-answer case.

Pattern 1: frequency counting plus an order-preserving pass

Practice question: Given a lowercase string s, print the first character whose total frequency is exactly 1. Print -1 if none exists.

For s = "success", the indices are 0:s, 1:u, 2:c, 3:c, 4:e, 5:s, 6:s. The first pass gives {s:3, u:1, c:2, e:1}. In the second pass, index 0 holds s with count 3, so skip it. Index 1 holds u with count 1, so return u.

Code
frequency = empty table
for ch in s:
    frequency[ch] += 1

for ch in s:
    if frequency[ch] == 1:
        return ch
return -1

Scanning an unordered map cannot reliably answer “first”, so rescan the original string. Time is O(n). Auxiliary space is O(k) for k distinct characters, or O(1) alphabet space when only 26 lowercase letters are allowed. Test "aabb" -> -1, "x" -> x, and empty input only if the prompt defines it.

Pattern 2: two pointers on a sorted pair-sum problem

Practice question: Given sorted array [2, 4, 7, 11, 15] and target 15, return zero-based indices of one matching pair, or [-1, -1] if none exists.

Start with left = 0, right = 4.

  1. (0,4) gives 2 + 15 = 17, too large, so set right = 3.

  2. (0,3) gives 2 + 11 = 13, too small, so set left = 1.

  3. (1,3) gives 4 + 11 = 15, so return [1,3].

The invariant is simple: in a sorted array, move right leftward to reduce a large sum, and move left rightward to increase a small sum. The scan is O(n) time and O(1) auxiliary space. Sorting unsorted input costs O(n log n) and may destroy original indices. For [1, 2, 4], target 8, the pointers cross and return [-1,-1].

Indexed array [2, 4, 7, 11, 15] with target 15 and three two-pointer steps ending at indices [1, 3].

Pattern 3: sliding window for the longest unique substring

Practice question: For s = "abcaefbb", return the length of the longest contiguous substring with no repeated character. The answer is 5. The first maximum is "bcaef"; "caefb" also has length 5.

Track each character’s latest index. Before measuring the window, update left = max(left, lastSeen[ch] + 1). The max stops a stale duplicate from moving left backwards.

r, character

left

Window

Length

maxLen

0, a

0

a

1

1

1, b

0

ab

2

2

2, c

0

abc

3

3

3, a

1

bca

3

3

4, e

1

bcae

4

4

5, f

1

bcaef

5

5

6, b

2

caefb

5

5

7, b

7

b

1

5

Time is O(n) and space is O(k) for tracked characters. Test "" -> 0, "bbbb" -> 1, and "ab" -> 2.

Eight-row trace of the longest unique windows in abcaefbb, with bcaef and caefb highlighted at length 5.

Pattern 4: run-length encoding without losing the final group

Practice question: Compress each consecutive run as its character followed by its count. For s = "aaabbccccd", return a3b2c4d1. For an empty string, return an empty string.

Start with current='a', count=1. The next two a characters make count=3. Seeing b emits a3 and resets the state to current='b', count=1; the next b makes 2. Seeing c emits b2. Four c characters produce count 4. Seeing d emits c4. After the loop, flush the still-open run and emit d1. The output is a3b2c4d1.

This is consecutive-run compression, not total frequency counting. It takes O(n) time, O(n) output space and O(1) working state apart from the output builder. Prefer a builder where repeated immutable-string concatenation is costly. Test "q" -> q1, "zzzz" -> z4, and "ab" -> a1b1.

Convert a correct idea into a judge-ready submission

Use this five-line audit for every solution:

  1. Copy the input and output contract exactly.

  2. Separate input parsing from the solving function.

  3. Initialise state for the smallest valid input.

  4. Print only the required result.

  5. State final complexity, including sorting or map costs.

Trace before execution. Pair sum must reproduce 17, 13, 15. The sliding window must reproduce left positions 0,0,0,1,1,1,2,7 and maxLen=5. The Pseudocode Questions for Placements lesson develops this trace-table habit. Then compare the same one-pass thinking under different wording in TCS Coding Questions. This teaches transfer without guessing a current platform, language rule or hidden-test format.

Traps that turn the right pattern into a wrong answer

Trap

Failure

Repair

Iterate the frequency map

Loses “first”

Rescan the original string

Move window left backwards

Admits an old duplicate

Use max(left, lastSeen[ch] + 1)

Sort when original indices matter

Returns wrong positions

Use a value-to-index map or preserve indexed pairs

Forget the post-loop flush

Drops d1

Emit the open run after the loop

Complexity claims also need honesty. Frequency counting and sliding windows are linear because each character is processed a bounded number of times. “Two pointers is O(n)” describes the scan, not an earlier O(n log n) sort. State both stages when both happen.

The short version and the next practice step

  • Frequency words mean count, then preserve order.

  • Sorted pair plus target means squeeze two pointers inward.

  • Longest contiguous condition means maintain a valid window.

  • Consecutive repeats mean track a run and flush the last one.

Without notes, reproduce success -> u, [2,4,7,11,15] + target 15 -> [1,3], abcaefbb -> 5, and aaabbccccd -> a3b2c4d1. Then change the values and solve them again. Use Coding for Placements for broader multi-language preparation.