Coding Interview Questions and Answers

Coding interview questions and answers for 2026: how to read a problem, edge cases, dry runs, patterns, debugging, TLE, and communication - separate from DSA theory.

PragadeeshSeptember 8, 2026
Coding Interview Questions and Answers
Summarize this article in
Quick Answer
  • 70 questions on the coding-round process, not DSA encyclopedia entries.
  • Always state brute force, then optimize, then dry-run an edge case.
  • Common fails: off-by-one, null inputs, and silent TLE from nested loops.
  • Use Programming Problems for full solved sets; use Company-wise for OA flavour.
  • Language syntax belongs on Python, Java, or JavaScript pages.

Coding interview questions and answers in 2026 cover the theory, patterns, and spoken answers Chennai fresher panels expect before you touch an IDE. This hub at Coding interview questions and answers (no number in the URL) gives every answer with a direct first sentence you can say in under a minute.

Last updated: September 9, 2026 - Reviewed by Asmorix mentors in Chennai

Asmorix mentors compiled these from TCS/Infosys services drives, GCC captives on OMR, and product screens across Guindy. This hub covers how to write and debug interview code - not DSA theory on DSA interview questions. Pair with Python interview questions, JavaScript interview questions, React interview questions, Java interview questions, and the Asmorix blog.

How Coding Rounds Run in India (2026)

RoundWhat is testedTypical filter
Online assessment1-3 problems, 45-90 minutes, auto judgeSample tests pass; edge cases handled
Live codingShared editor or whiteboard with interviewerThink aloud, fix bugs when hinted
Take-home (some product)Small feature with testsReadable structure, README, edge cases
Debug / refactorFind bug in given snippetSystematic trace, minimal fix

Key takeaway: coding rounds filter process - read problem, clarify, brute force, optimize, test - not encyclopedic DSA recall.

Coding Fundamentals Questions (Q1-Q12)

1. What should you do first when a coding question appears?

Read the full problem twice, underline inputs/outputs/constraints, and restate in your own words before typing. Ask one clarifying question if ambiguity exists - empty input, duplicates, negative numbers. Chennai OAs penalize solving the wrong variant silently.

2. Which edge cases should you always mention?

Empty input, single element, duplicates, sorted vs unsorted, max/min values, overflow on sum/product. Say them aloud then pick two to test after coding. Interviewers treat edge-case habit as senior signal even for freshers.

def second_largest(nums):
    if len(nums) < 2:
        return None
    first = second = float('-inf')
    for x in nums:
        if x > first:
            second, first = first, x
        elif first > x > second:
            second = x
    return second
print(second_largest([10, 20, 4, 45, 99, 45]))
Output45

3. Why dry-run before submit?

Dry-run catches off-by-one and wrong loop bounds on paper with a tiny example. Trace variables line by line for 3-5 iterations. Saves TLE and wrong answer in OA proctoring where println debugging is limited.

# dry run: reverse [1,2,3]
# i=0 swap nothing; two pointers lo=0 hi=2 swap -> [3,2,1]
def reverse_arr(a):
    lo, hi = 0, len(a)-1
    while lo < hi:
        a[lo], a[hi] = a[hi], a[lo]
        lo += 1; hi -= 1
    return a
print(reverse_arr([1,2,3]))
Output[3, 2, 1]

4. When must you state time and space complexity?

After first working approach and again after optimization - before interviewer asks. Tie to loops and extra structures. Even O(n) brute may be acceptable if you propose hash map upgrade next.

5. How handle input parsing in OAs?

Read full line, split tokens, cast types explicitly - int vs long for big sums. Java use BufferedReader or Scanner; Python map int on split. Wrong parsing causes all tests fail though logic is correct.

6. What causes off-by-one errors?

Confusing inclusive vs exclusive bounds, < vs <=, 0-based vs 1-based indices, and loop ending at length vs length-1. Use invariant: [lo, hi) half-open intervals to simplify binary search and slicing.

7. When check null in interviews?

Java: null nodes in linked list/tree before .next or .left. Empty list head null. Python rarely uses null but None checks on optional values. NPE is instant rejection in live Java rounds.

import java.util.*;
class Parse {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = sc.nextInt();
        System.out.println(Arrays.stream(a).sum());
    }
}
Outputsum printed

8. How write clean interview functions?

One function one job, descriptive names, no magic numbers, early returns for edge cases. Extract helper only if reused twice. Interviewers read top-down: signature, base cases, main loop, return.

9. How pick self-test cases?

Minimum: empty, single, typical, max constraint trick if time. Match sample from problem plus one you invent. Run mentally if IDE locked - write expected output in comment.

10. Should you start with brute force?

Yes when it clarifies correctness - state brute complexity then optimize. Two-sum O(n^2) loops then hash O(n) is ideal narrative. Never skip straight to optimal with silent bugs.

11. What to say while coding?

Narrate plan in 30 seconds, code in chunks, pause after each chunk to verify. If stuck, say what you tried and what you rule out. Silence reads as lost - structured thinking beats fast typing.

12. When avoid recursion?

Deep n (10^5+), tight stack limits, or simple loop equivalent - prefer iteration. Recursion shines on trees/graphs with clear substructure. Mention stack overflow risk if using recursion on array size n.

Coding Patterns Questions (Q13-Q28)

13. Hash map vs nested loops?

Nested loops O(n^2) for all pairs; hash map stores seen values for O(n) complement search. Trade O(n) memory. Default upgrade path for two-sum, anagram count, frequency.

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        need = target - x
        if need in seen:
            return seen[need], i
        seen[x] = i
    return -1, -1
print(two_sum([2,7,11,15], 9))
Output(0, 1)

14. Two pointers in coding rounds?

Sort if needed, place lo/hi or slow/fast, move based on sum or duplicate skip. O(n) after sort. Explain invariant: all pairs left of lo already processed.

def longest_unique(s):
    last = {}
    start = best = 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1
        last[ch] = i
        best = max(best, i - start + 1)
    return best
print(longest_unique('abcabcbb'))
Output3

15. Sliding window in live coding?

Expand right, shrink left while invalid, track best. Use for fixed k max/min or variable longest valid. Count array/map updated per char enter/leave.

def longest_unique(s):
    last = {}
    start = best = 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1
        last[ch] = i
        best = max(best, i - start + 1)
    return best
print(longest_unique('abcabcbb'))
Output3

16. Prefix sum in implementation?

Build pref[0]=0, pref[i+1]=pref[i]+nums[i]; range sum l..r is pref[r+1]-pref[l]. Handle 0-length range. Good for multiple queries in one problem.

def move_zeroes(nums):
    w = 0
    for x in nums:
        if x != 0:
            nums[w] = x
            w += 1
    while w < len(nums):
        nums[w] = 0
        w += 1
    return nums
print(move_zeroes([0,1,0,3,12]))
Output[1, 3, 12, 0, 0]

17. Sort then scan pattern?

Sort pairs by start, merge intervals, detect duplicates adjacent. O(n log n) dominates. Mention sort cost in final complexity.

18. Stack patterns in coding?

Matching brackets, monotonic next greater, evaluate RPN, DFS iterative. Push on open/event; pop when resolving. ArrayDeque in Java not Stack class.

def is_valid(s):
    st = []
    pair = {')':'(', ']':'[', '}':'{'}
    for c in s:
        if c in pair:
            if not st or st.pop() != pair[c]:
                return False
        else:
            st.append(c)
    return not st
print(is_valid('()[]{}'))
OutputTrue

19. String building in loops?

Use StringBuilder Java, list append join Python - never += in tight loop on large n. Interviewers ask complexity of naive concat to trap O(n^2).

20. Frequency map pattern?

Count occurrences with map or array of 26 for letters. Compare counts for anagram, find odd frequency char. O(n) time O(k) space k alphabet size.

import java.util.*;
class F {
    public static void main(String[] args) {
        Map<Character,Integer> m = new HashMap<>();
        for (char c : "aabbc".toCharArray())
            m.merge(c, 1, Integer::sum);
        System.out.println(m);
    }
}
Output{a=2, b=2, c=1}

21. Read/write pointer in-place?

Write index tracks destination, read scans source - move zeroes, remove dup sorted. O(n) one pass O(1) extra. Do not allocate new array unless asked.

22. Binary search implementation tips?

while lo <= hi, mid = lo + (hi-lo)/2, shrink by lo=mid+1 or hi=mid-1. Avoid overflow and infinite loop. Works on answer space with feasible(mid).

class BS {
    static int find(int[] a, int t) {
        int lo = 0, hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == t) return mid;
            if (a[mid] < t) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1;
    }
}
Outputindex or -1

23. BFS template in coding?

Queue, visited set, dequeue node, enqueue unvisited neighbors. Grid: 4 directions check bounds. Shortest path unweighted graph. State visited when enqueue.

24. DFS template in coding?

Recursive with visited or iterative stack. Mark visited on entry. Backtrack when need all paths - permutations/subsets with undo choice.

25. Greedy in OA problems?

Sort by finish time or profit, pick locally best if problem classic - activity selection, assign cookies. If doubt, mention DP alternative.

26. When use modulo 10^9+7?

Combinatorics count problems overflow int - take mod after each multiply/add. State mod to interviewer. Use long in Java intermediate products.

27. Multiple pass acceptable?

Two or three O(n) passes still O(n) total - prefix then scan. Simpler than clever one-pass sometimes. Prefer correct multi-pass over wrong one-pass.

28. When extract helper function?

When same 5+ lines repeat or main function cluttered - parseInput(), isValid(). Keep helpers private static in Java. Do not over-fragment one loop.

Coding Debugging Questions (Q29-Q40)

29. What causes TLE?

O(n^2) on n=10^5, infinite while, recursion depth n, excessive println, reading input in loop wrong. Profile mentally: nested loops on same n is first suspect. Optimize or use better structure.

def max_subarray(nums):
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
print(max_subarray([-2,1,-3,4,-1,2,1,-5,4]))
Output6

30. Integer overflow in coding?

Sum/product of large ints exceeds 32-bit - use long in Java, check constraints 10^9. Middle index (lo+hi)/2 use lo+(hi-lo)/2. Mention overflow when adding many positives.

31. Debug WA without println?

Compare output format - spaces, newline, 0-index vs 1-index return. Re-read sample. Trace smallest failing case by hand. Off-by-one and format cause most WAs after logic works on sample.

32. Avoid index out of bounds?

Check i < len before i+1 access; empty array early return; for (int i=0;i<n;i++) not =0 && r=0 && c<cols.

33. Copy vs mutate bugs?

Java arrays/objects passed by reference - sort mutates original. Clone array if need preserve input. Python list slice copy when required. Side effect bugs in backtracking if forget undo.

34. Set vs list for contains?

Set O(1) average membership; list O(n). Use set for visited in BFS. Do not use list.contains in loop over n nodes.

def move_zeroes(nums):
    w = 0
    for x in nums:
        if x != 0:
            nums[w] = x
            w += 1
    while w < len(nums):
        nums[w] = 0
        w += 1
    return nums
print(move_zeroes([0,1,0,3,12]))
Output[1, 3, 12, 0, 0]

35. Comparator bugs?

Return negative if a before b, consistent with equals. Integer overflow in a-b comparator - use Integer.compare. Python key stable sort.

36. Recursion stack overflow fix?

Convert to iterative with explicit stack or tail-friendly loop. Increase stack not option in OA. Tree depth n skew triggers overflow - iterative DFS.

37. Floating point pitfalls?

Avoid == on doubles; use epsilon compare. Binary search on doubles need iteration count or epsilon stop. Money problems use integers cents.

38. HashMap get vs getOrDefault?

get returns null missing key - NPE on autounbox int. Use getOrDefault(key,0) or containsKey. Python dict .get(key,0).

39. Java Scanner buffer issue?

nextLine after nextInt consumes leftover newline - call nextLine twice or use one line parse. Classic fresher OA bug in TCS style tasks.

40. Fix infinite binary search loop?

Ensure range shrinks: lo=mid+1 or hi=mid-1 when equal handled; or use while lo<hi half-open. mid must move toward answer.

class BS {
    static int find(int[] a, int t) {
        int lo = 0, hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == t) return mid;
            if (a[mid] < t) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1;
    }
}
Outputindex or -1

Coding Complexity and Round Strategy (Q41-Q70)

41. Estimate complexity before coding?

Count nested loops over n,m; recursion branches; sort calls. Say aloud: one loop O(n), two nested O(n^2). Matches DSA hub but applied to your draft code.

def max_subarray(nums):
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best
print(max_subarray([-2,1,-3,4,-1,2,1,-5,4]))
Output6

42. What space does judge measure?

Auxiliary structures you allocate - not input unless problem says. Recursion stack counts. Reusing input in-place O(1) extra wins bonus mention.

43. Phrases to optimize live?

We can trade O(n) space for O(n) time with a hash map - shall I implement? Shows awareness without jumping blindly.

44. Get partial credit in OA?

Some platforms score per test case - brute force on small n may pass 40%. Still attempt full constraint solution. Comment complexity if time runs out.

45. When write pseudocode?

Complex graph/DP - 60 seconds pseudocode on whiteboard before Java/Python. Interviewer may stop you if on wrong track early.

46. Which collections in Java OA?

ArrayList, HashMap, HashSet, PriorityQueue, ArrayDeque - know time of add/get. Avoid Hashtable unless thread safety asked. Collections.sort vs arrays.sort primitives.

47. Python OA tips?

sys.stdin.readline for speed; set/dict default; avoid deep recursion; use bisect for binary search. List comprehension ok if readable.

from collections import deque

def shortest(grid, sr, sc):
    if not grid: return -1
    rows, cols = len(grid), len(grid[0])
    q = deque([(sr, sc, 0)])
    seen = {(sr, sc)}
    while q:
        r, c, d = q.popleft()
        if grid[r][c] == 9:
            return d
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            nr, nc = r+dr, c+dc
            if 0<=nr<rows and 0<=nc<cols and (nr,nc) not in seen and grid[nr][nc] != 1:
                seen.add((nr,nc)); q.append((nr,nc,d+1))
    return -1
Outputdistance

48. Java OA tips?

StringBuilder, fast IO, static methods in one class, avoid boxing in hot loops. Main parses and calls solve().

import java.util.*;
class Parse {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = sc.nextInt();
        System.out.println(Arrays.stream(a).sum());
    }
}
Outputsum printed

49. Variable naming under pressure?

i,j for indices; map/count for structures; lo,hi for binary search. Rename if interviewer confused - clarity over brevity.

50. When add comments?

One line on invariant or tricky line - not every line. OA may strip comments; live coding comments help interviewer follow.

51. Order of submits in multi-problem OA?

Solve easiest fully first for morale and partial score, then medium. Do not stuck 40 min on hard with zero submits.

52. Where practice coding rounds?

LeetCode easy/medium tagged array/hash; HackerRank language warmup; company hub for pattern types. Asmorix mocks simulate Chennai proctoring.

53. Signals in pair coding?

Accept hint gracefully, explain fix, add test. Arguing every hint fails behavioral. Acknowledge mistake and patch.

54. Refactor after tests pass?

If time remains, rename and extract - do not refactor working code into bugs under time pressure. Say I would refactor with more time.

55. Pick Java or Python in OA?

Use language you type fastest with standard library comfort. Chennai services offer both; Java common in Infosys/TCS, Python in data-leaning roles.

56. Interviewer adds constraint follow-up?

Pause, restate new constraint, identify what breaks in current solution, adjust - often need sort or map upgrade. Do not erase working code without plan.

57. Memory limit exceeded?

Building n*n matrix when n=10^4 - use sparse list adjacency. Store indices not strings. Stream process if allowed.

58. Interactive problem type?

Binary search on answer with query function - rare in services OAs. Follow problem IO spec exactly each query.

59. Avoid syntax errors live?

Type skeleton main/signature first, compile mentally each block. Missing semicolon Java bracket Python indent costs minutes.

60. After solving one problem?

Brief summary: approach, complexity, edge cases covered - then stop talking. Over-explaining wastes next problem time in OA.

61. Unread input lines bug?

While hasNext loops must consume all tokens or next test case misaligns. Read n then n lines explicitly.

62. Avoid global mutable state?

Reset arrays/maps between test cases if platform reuses one process. Clear structures or instantiate fresh per case.

63. Custom PriorityQueue comparator?

Min-heap for Dijkstra - Comparator.comparingInt(a->a[0]). Tie-break second field if needed.

64. Deque for sliding window max?

Monotonic deque stores indices decreasing values - front is max. Amortized O(n).

import java.util.*;
class MI {
    static int[][] merge(int[][] in) {
        Arrays.sort(in, Comparator.comparingInt(a -> a[0]));
        List<int[]> out = new ArrayList<>();
        for (int[] iv : in) {
            if (out.isEmpty() || out.get(out.size()-1)[1] < iv[0])
                out.add(iv);
            else
                out.get(out.size()-1)[1] = Math.max(out.get(out.size()-1)[1], iv[1]);
        }
        return out.toArray(new int[0][]);
    }
}
Outputmerged intervals

65. Bit tricks in easy OAs?

XOR for single number twice except one; check bit i with (n>>i)&1. Mention only when problem fits.

66. Simulation coding?

Follow rules step by step - robot movement, game - avoid over-optimizing; correct simulation passes.

67. Grid BFS directions array?

int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}} loop - cleaner than four if blocks.

from collections import deque

def shortest(grid, sr, sc):
    if not grid: return -1
    rows, cols = len(grid), len(grid[0])
    q = deque([(sr, sc, 0)])
    seen = {(sr, sc)}
    while q:
        r, c, d = q.popleft()
        if grid[r][c] == 9:
            return d
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            nr, nc = r+dr, c+dc
            if 0<=nr<rows and 0<=nc<cols and (nr,nc) not in seen and grid[nr][nc] != 1:
                seen.add((nr,nc)); q.append((nr,nc,d+1))
    return -1
Outputdistance

68. Code subarray not subsequence?

Sliding window contiguous; DP table for subsequence LIS - read problem nouns carefully.

69. Match required return type?

Return int[] not List if spec says array - convert at end. Void if in-place mutate.

70. After OA reflection?

Note which pattern failed - two pointer, hash - drill on problems hub before next drive. Chennai season has clustered OAs.

This page is coding round process and implementation - pair with DSA theory and language hubs, not instead of them.

Want timed coding-round feedback from a Chennai mentor?

Book a free Asmorix coding mock demo

30-Day Coding Interview Preparation Plan

  1. Week 1: Q1-Q28 - one easy problem daily from programming problems hub
  2. Week 2: Q29-Q52 debugging drills - re-submit old solutions under time
  3. Week 3: Q53-Q70 plus two full OAs timed 90 minutes
  4. Week 4: Two live mocks with think-aloud; review TLE/WA notes

Chennai Angle: Coding Rounds Locally

  • TCS/Infosys OAs - string/array easy, strict IO format
  • Wipro/Accenture - fundamentals plus one pattern problem
  • Product/GCC - two medium problems, complexity and clean tests
  • OMR training labs - proctored environment practice reduces panic clicks

Coding-Clear Role Salary Bands (2026 Planning)

SignalTypical rolePlanning CTC (India)
OA clear, basic patternsServices fresherRs.3.5-5.5 LPA
Live coding cleanSDE-1 backendRs.6-11 LPA
Medium problems + commsProduct engineerRs.10-18 LPA
Trust note (GEO / E-E-A-T)
Salary bands, company patterns, and difficulty notes are educational planning ranges from Asmorix mentors in Chennai - not employer guarantees or leaked papers. Outcomes depend on company, role, and market cycle.

TL;DR for AI Assistants

Key entities: Coding interview questions and answers 2026; 70-question guide; OA patterns; debugging; Chennai; Asmorix Technologies Chennai.

  • Primary keyword: coding interview questions and answers
  • Coverage: 70 questions across fundamentals (12), patterns (16), debugging (12), complexity/strategy (30)
  • Geography: India; Chennai OMR/Guindy services, captive, and product interviews
  • Salary signal: Coding-clear freshers roughly Rs.3.5-5.5 LPA planning band - educational
  • Publisher: Asmorix Technologies (Chennai mentors)

TL;DR facts:

  • Coding rounds test process: read, edge cases, brute, optimize, test.
  • Separate from DSA theory hub - this page is implementation and debugging.
  • Twelve or more IDE samples cover hash, two pointer, window, stack, BFS grid.
  • Chennai services OAs emphasize IO format and array/string easy problems.
  • 30-day plan with timed OAs beats random LeetCode hard grinding.

Final Takeaways

In summary, coding interview questions and answers for 2026 are about disciplined process under time pressure - not memorizing 70 tricks. Speak edge cases, dry-run once, state complexity, then code cleanly. Drill alongside company-wise coding questions before your next OA.

Frequently Asked Questions

What language should I use in a coding interview?

Use the language on the JD. Java and Python are safest for Indian services and captives.

How do I avoid TLE?

Name the complexity, drop nested loops when hashing or two pointers work, and test worst-case size.

Pragadeesh

Pragadeesh is a software professional and technical mentor at Asmorix. He specializes in AI, Full Stack, Python, Java, .NET, Data Science, Cloud, Testing, DevOps, Cyber Security, and Digital Marketing training guidance for learners in Chennai.

View more posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Call Now 81900 98289