Coforge Coding Questions: Three Patterns with Solved Examples
Recognising a coding problem is only the start. Practise second distinct maximum, first non-repeating character and maximum subarray sum with complete Python functions and edge-case checks.
KnowledgeGate Team
Exam prep & CS education

You recognise a coding question, but choosing the variables still takes too long. Then a duplicate value or an all-negative array breaks the solution that passed the sample. These three solved exercises build reusable methods for Coforge preparation: decide what to remember, trace each update, and test the cases that expose a wrong assumption before you submit.
Choose the pattern before writing code
Write down the input, required output and constraints first. Then choose an invariant, a fact that remains true after each iteration. It explains why your stored state is enough.
Problem | State to maintain |
|---|---|
Second distinct maximum | Two largest distinct values seen |
First non-repeating character | Frequencies, then original order |
Maximum contiguous sum | Best ending here and best overall |
An array is the complete indexed sequence; a contiguous subarray occupies consecutive positions within it. A distinct value is a different value, not another occurrence of the same number.
Python 3 makes the retained state visible in each function. The traces show how a duplicate, a late character, or a negative value changes that state. If loops or dictionaries are unfamiliar, revise language fundamentals through Coding & Skills.
Array scan: find the second distinct maximum
Given an integer list, return its second largest distinct value, or None if fewer than two distinct values exist. For [12, 7, 12, 9, 3], the answer is 9.
Sorting gives an O(n log n) baseline, but two trackers avoid sorting. After each element, largest and second hold the two largest distinct values seen, with None marking a missing value.
def second_distinct(a):
largest = second = None
for x in a:
if largest is None or x > largest:
second, largest = largest, x
elif x != largest and (second is None or x > second):
second = x
return secondReading 12 gives (12, None). Reading 7 gives (12, 7). The second 12 leaves (12, 7) unchanged: another maximum is not a second distinct value. Reading 9 updates the pair to (12, 9); reading 3 leaves it there.
![Trace table for a second-distinct-maximum scan of [12, 7, 12, 9, 3], ending with largest 12, second 9, and the duplicate 12 skipped.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1790077291797_uu253b.jpg)
When a new maximum arrives, the old maximum becomes second. Otherwise, only a distinct value larger than second replaces it. This takes O(n) time and O(1) auxiliary space.
Check [5, 5] -> None, [-8, -3, -5] -> -5, [] -> None and [4] -> None. Initialising both trackers to zero fails for all-negative inputs because zero would incorrectly outrank every input value.
String scan: find the first non-repeating character
For a string containing lowercase English letters, return the first character whose total frequency is one. Return None when no such character exists. “First” means input order, not alphabetical order.
def first_unique(s):
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch in s:
if freq[ch] == 1:
return ch
return NoneFor aabbcd, the indexed characters are 0:a, 1:a, 2:b, 3:b, 4:c, 5:d. Final frequencies are a:2, b:2, c:1, d:1.
The second pass skips indices 0 through 3 because a and b repeat, then returns c at index 4. d also occurs once, but it appears later.
After the first pass, every stored frequency describes the whole input. Choosing a character before finishing this pass is unsafe: in aab, the first a looks unique until the second a arrives.
Tests: aabb -> None, aabbcd -> c, empty string -> None, z -> z, and bbaaac -> c. Two scans still take O(n) time. The dictionary uses O(k) space for k distinct characters, bounded by 26 under this alphabet. The function does not change case or remove whitespace; those would be different input rules.
The earlier Wipro Coding Questions: 3 Solved Patterns with Step-by-Step Traces uses the swiss frequency trace and stable compaction; this Coforge set uses aabbcd and focuses on distinct-extrema and maximum-subarray invariants.
Contiguous sums: extend or restart the subarray
For a non-empty integer list, return the maximum sum of a non-empty contiguous subarray. In [-2, 3, -1, 4, -5], indices 1 through 3 give [3, -1, 4], with sum 3 - 1 + 4 = 6. Selecting only positives gives 7 but skips the intervening -1, violating contiguity.
def max_subarray_sum(a):
if not a:
raise ValueError("Input must be non-empty")
ending = best = a[0]
for i in range(1, len(a)):
ending = max(a[i], ending + a[i])
best = max(best, ending)
return bestThis is Kadane's recurrence. A segment ending here either starts here or extends the best segment ending immediately before it. ending stores that local optimum; best stores the largest sum found anywhere so far.
x | Calculation for ending | ending | best |
|---|---|---|---|
-2 | Initialise | -2 | -2 |
3 | max(3, -2 + 3) | 3 | 3 |
-1 | max(-1, 3 - 1) | 2 | 3 |
4 | max(4, 2 + 4) | 6 | 6 |
-5 | max(-5, 6 - 5) | 1 | 6 |
![Indexed array [-2, 3, -1, 4, -5] highlights contiguous subarray [3, -1, 4], with ending sums -2, 3, 2, 6, 1 and best sum 6.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1790077292868_qvmt42.jpg)
Initialising from the first element handles [-6, -2, -9] -> -2 and [4] -> 4. Empty input raises ValueError. The indexed loop avoids copying a slice, giving O(n) time and O(1) auxiliary space. Extend your practice with DSA Interview Questions: 7 Patterns for Placements.
Hidden-case traps that change the answer
Use these checks before trusting a sample output.
Failure | Fix |
|---|---|
Duplicate maxima occupy both trackers | Enforce distinctness |
Zero initialisation breaks negative inputs | Use |
An early “unique” character repeats later | Finish the count pass |
Adding positives skips internal negatives | Preserve contiguity |
Debug prints spoil the expected output | Print only the specified result |
Internal None means “no answer” in the first two functions. If a prompt requires -1, convert at the output boundary. Do not assume -1 is universally safe for numerical answers: it can also be a valid result. In C++ or Java implementations, choose an integer type wide enough for the possible sums to avoid fixed-width overflow.
How to use these patterns in a Coforge assessment
These are practice problems for Coforge preparation, not verified past Coforge questions. Coforge's careers site is the official recruitment starting point; follow your own assessment invitation for the format and allowed languages.
Choose a 30-minute practice drill for yourself:
4 minutes: restate the input, output and missing-answer rule.
6 minutes: derive the state and trace an example.
14 minutes: implement the function and required input/output handling.
6 minutes: run edge cases and inspect failures.
These allocations total 30 minutes and are a practice choice. Say the invariant and complexity aloud before coding. If you cannot explain why an update preserves the invariant, revisit that step.
On the next attempt, change one condition, such as finding the third distinct maximum. For general question selection and time management, use Coding Round Strategy: Triage, Time-Box, Bank Marks.
The short version and your next practice step
Two maxima preserve ordering and distinctness. Frequency counts separate “occurs once” from “appears first”. Kadane's recurrence preserves contiguity while choosing between extending and restarting.
Close the solutions and reproduce the three functions with the given edge cases. Then implement your weakest pattern in your chosen language and explain why every state update is correct. Check the missing-answer behaviour as carefully as the successful case.
If you want structured language and coding practice, Coding for Placements covers C, C++, Java and Python as part of broader placement preparation. Use that practice to strengthen the method you found hardest to explain.
Keep learning
Publicis Sapient Coding Questions: Three Patterns with Worked Solutions
Recognising code is easier than explaining why it works. Practise three patterns through Java methods, exact traces, invariants and edge cases before your next coding assessment.
JPMorgan Chase Coding Questions: Three Patterns with Solved Examples
Know a solution but struggle when the input changes? Practise complement lookup, sliding windows and take-or-skip dynamic programming with exact traces and clear invariants.
Wells Fargo Coding Questions: Three Patterns with Worked Solutions
Learn to recognise three coding patterns from the task itself. Follow complete Python solutions, trace each state change, and catch mistakes involving duplicate values, repeated characters and negative numbers.
Coforge Interview Questions: Technical and HR Answers for Freshers
Practise explaining Java behaviour, tracing a coding solution and defending a SQL query. Use project follow-ups and honest HR templates to build answers you can support with evidence.





