Top 50 Infosys Coding Questions
SE · DSE · SP Roles
Most-asked questions from Infosys coding rounds 2021–2026 — Easy, Medium & Hard — covering every topic that appears in SE, DSE, and SP / HackWithInfy assessments.
These questions are drawn from candidate-reported experiences across Infosys hiring cycles 2021–2026, covering the Systems Engineer (SE) on-campus track, Digital Specialist Engineer (DSE), and Specialist Programmer (SP) / HackWithInfy assessments. The coding round has 3 questions in 3 hours: Easy (20 marks), Medium (30 marks), Hard (50 marks). Questions are presented as-is — no resource names attached.
| Role | Questions | Duration | Easy Topic | Medium Topic | Hard Topic |
|---|---|---|---|---|---|
| SE | 2 | 90 min | Arrays / Strings | Greedy / Sorting | — |
| DSE | 3 | 3 hrs | DS Basics | Greedy / DP | DP / Graphs |
| SP (HackWithInfy) | 3 | 3 hrs | Simulation / Arrays | Greedy + Bit Manip | DP / XOR / Graphs |
Questions 1–20 are the most commonly asked Easy-level questions across SE on-campus rounds and as Q1 in DSE/SP tests (2021–2026).
Given an array of N integers, reverse it in-place and print the result.
Approach: Two-pointer — swap A[left] and A[right], move pointers inward until they cross.
Given a string S, determine whether it reads the same forwards and backwards (palindrome). Ignore case.
Approach: Compare S with its reverse; or use two pointers from both ends.
Find the second largest distinct element in an array of N integers. If no such element exists, return -1.
Approach: Single pass — maintain two variables: first and second. Update both as you iterate.
Given a string, count the number of vowels (a, e, i, o, u — case insensitive) and consonants separately.
Approach: Iterate each character; skip spaces; check against vowel set for classification.
An array contains N-1 distinct integers in the range [1, N]. Exactly one number is missing. Find it.
Approach: Compute expected sum = N*(N+1)/2 and subtract array sum. Or use XOR.
Given an integer N (N ≥ 2), determine whether it is a prime number.
Approach: Check divisibility from 2 to √N. If any divisor found → not prime.
Given N, print the first N terms of the Fibonacci sequence.
Approach: Use two variables a=0, b=1; print a, then update a,b iteratively N times.
Given a sorted array A of N integers and a target T, return the index of T in A. If not found, return -1.
Approach: Maintain low and high pointers; check mid; halve the search space each iteration.
Given the head of a singly linked list, reverse it in-place and return the new head.
Approach: Use three pointers: prev=NULL, curr=head, next. Reverse curr.next = prev and advance.
Given two strings S and T, determine if they are anagrams of each other (same characters, same frequency, different order).
Approach: Sort both strings and compare, or use a frequency HashMap (count up for S, count down for T).
Given an array of N integers where elements are in range [1, N], find all elements that appear more than once.
Approach: For each A[i], negate A[abs(A[i])-1]. If it's already negative, that index+1 is a duplicate.
Given an array A of N integers and an integer K, rotate the array to the right by K steps.
Approach: Reverse whole array → reverse first K → reverse remaining N-K. Effective K = K % N.
Given an N×N square matrix, find the sum of elements on its primary and secondary diagonals. Count the centre element only once for odd N.
Approach: Single pass — add A[i][i] and A[i][N-1-i]; subtract A[N/2][N/2] once when N is odd.
Sort an array of N integers in ascending order using Bubble Sort. Print the sorted array.
Approach: Repeatedly swap adjacent elements if out of order. Optimise with a swapped flag to exit early if already sorted.
Given a positive integer N, determine if it is a power of 2.
Approach: Use bit trick: N > 0 && (N & (N-1)) == 0. Powers of 2 have exactly one set bit.
You are given a string number representing a positive integer and a digit d. Remove exactly one occurrence of digit d from number so that the resulting number is the maximum possible.
Approach: Scan left to right; remove the first occurrence of d where the next digit is greater than d. If none found, remove the last occurrence.
Given an array A of N integers, count: (1) how many distinct values appear more than once, and (2) how many distinct values appear exactly once.
Approach: Build a frequency HashMap; scan entries — count those with freq > 1 as repeated, freq == 1 as non-repeated.
Given the root of a binary tree, return its zigzag level-order traversal (alternate left-to-right and right-to-left per level).
Approach: BFS with a deque; toggle a direction flag per level to decide whether to append front or back.
Given an array A of N integers, for each element find the smallest power of 2 that is ≥ that element.
Approach: For each value, if already a power of 2 return it. Otherwise find MSB position and return 2^(position+1).
Given a string S, find the first character that does not repeat. Return the character; if none, return '#'.
Approach: Build a frequency array (size 26) in one pass; scan string again and return the first character with freq=1.
Questions 21–35 are Medium-level problems (Greedy, Sliding Window, DP intro, Trees, Stack/Queue). These appear as Q2 in DSE/SP assessments and cover the bulk of HackWithInfy Round 1 mid-section.
Given a string S, find the length of the longest substring with all unique characters.
Approach: Sliding window + HashMap. Move right pointer; if duplicate found, move left pointer past the previous occurrence.
Given an array of integers representing a permutation, rearrange it into the lexicographically next greater permutation. If it's the largest, rearrange to the smallest (ascending order). Modify in-place.
Approach: Find rightmost index i where A[i] < A[i+1]. Swap A[i] with the smallest element greater than it to the right. Reverse the suffix from i+1 onward.
Given a linked list, detect whether it contains a cycle. Return true if a cycle exists, false otherwise.
Approach: Floyd's Cycle Detection — use two pointers (slow moves 1 step, fast moves 2). If they meet, a cycle exists.
Given an integer array A, find the contiguous subarray that has the largest product and return that product.
Approach: Track both max and min product at each position (min can turn max after multiplying a negative). Update global max each step.
Given a string containing only '(', ')', '{', '}', '[', ']', determine if the input string is valid. An input string is valid if every open bracket has a matching close bracket in the correct order.
Approach: Use a stack — push open brackets; on a close bracket, check if the stack top matches; if not or stack empty → invalid. Valid if stack is empty at the end.
Given a string S of length N, find the longest substring that is a palindrome. If multiple exist with equal length, return the one with the smaller starting index.
Approach: Expand-around-centre for each character (both odd and even lengths). Track the longest found. DP table also works in O(n²).
Given a list of intervals [start, end], merge all overlapping intervals and return a list of non-overlapping intervals.
Approach: Sort by start time. Iterate — if current interval overlaps the last merged one, extend end; otherwise push to result.
Given an array of N integers, find the length of the longest strictly increasing subsequence.
Approach: Patience sorting — maintain a tails array; binary search to find the position to replace. Length of tails array = LIS length.
Given a string S and a dictionary of words, determine if S can be segmented into a space-separated sequence of one or more dictionary words.
Approach: DP — dp[i] = true if S[0..i-1] can be segmented. For each i, check all j < i: if dp[j] and S[j..i-1] in dict → dp[i]=true.
Given a stack, reverse it using only recursion — no loops or extra data structures allowed.
Approach: Pop all elements recursively to the call stack, then use a helper insertAtBottom() to reinsert them — effectively reversing the order.
Given an array A of N non-negative integers and a target sum S, determine if there exists a subset of A whose elements sum to exactly S.
Approach: DP table dp[i][j] = true if subset of A[0..i-1] sums to j. Build bottom-up.
Given the head of a singly linked list, determine whether it reads the same forwards and backwards.
Approach: Find mid with slow/fast pointers → reverse second half → compare with first half → restore (optional).
Given an array of distinct integers candidates and a target integer target, find all unique combinations of candidates that sum to target. You may use the same number more than once.
Approach: Backtracking — for each candidate, recurse with remaining target; include same candidate again (unbounded). Prune when remaining < 0.
Design and implement a Trie data structure that supports: insert(word), search(word) — returns true if word is in trie, startsWith(prefix) — returns true if any inserted word has this prefix.
search("app") → false
startsWith("app") → trueOutput:As above
Approach: Each TrieNode has an array of 26 children (for 'a' to 'z') and an isEnd flag. Insert/Search traverse character by character.
Design a data structure that follows Least Recently Used (LRU) cache policy. It should support get(key) and put(key, value), both in O(1) time. Cache capacity is given at initialisation.
Approach: Combine a HashMap (key → node) with a Doubly Linked List (most recent at front). On access/insert, move node to front; on capacity overflow, remove from rear.
Questions 36–50 are Hard-level problems from DSE Q3, SP Q2–Q3, and HackWithInfy rounds (2021–2026). These involve DP, Greedy with Bit Manipulation, Graphs, and advanced combinatorics.
You are playing an RPG with N monsters. Monster i has a power[i] required to defeat it and grants bonus[i] experience after defeat. You start with e experience points. You can fight monsters in any order. To defeat monster i you need current experience ≥ power[i]; after defeating it, experience += bonus[i]. Find the maximum number of monsters you can defeat.
Approach: Sort monsters by power ascending. Greedily defeat as many as possible in order of power. If stuck, try swapping — greedy on sorted order is provably optimal.
Given an array A of N integers and an integer K, define Xor-Sum(x) = (x XOR A[1]) + (x XOR A[2]) + ... + (x XOR A[N]). Find the integer x in the range [0, K] that maximises Xor-Sum(x). Print the maximum Xor-Sum value.
Approach: For each bit position, decide whether setting that bit in x increases the sum without exceeding K. Process from MSB to LSB (greedy bit-by-bit selection within K constraint).
Given an array A of N integers, an operation type (AND / OR / XOR), and a target value, find the length of the Longest Increasing Subsequence (LIS) where adjacent elements in the subsequence satisfy: A[i] OP A[j] == target.
Approach: Modify standard LIS DP. dp[i] = length of valid subsequence ending at index i. For each j < i, if A[j] OP A[i] == target and A[j] < A[i], update dp[i] = max(dp[i], dp[j]+1).
Given an array A of N integers, split it into exactly K consecutive non-empty segments. The cost of a segment is the sum of its elements. Minimise the sum of costs across all K segments. (Note: since every element must belong to some segment, total cost = total array sum regardless of split — the challenge variant asks to minimise the maximum segment sum.)
Approach: Binary search on the answer (minimum possible max sum). For a given mid, greedily check if array can be split into ≤ K parts with each part ≤ mid.
Given coin denominations and an amount, find the minimum number of coins that make up that amount. You may use each coin denomination any number of times. Return -1 if not possible.
Approach: DP. dp[i] = min coins for amount i. For each coin, dp[i] = min(dp[i], dp[i-coin]+1).
Given two strings S and T, find the minimum number of single-character edit operations (insert, delete, replace) required to convert S into T.
Approach: 2D DP. dp[i][j] = edit distance between S[0..i-1] and T[0..j-1]. If chars match: dp[i-1][j-1]; else 1 + min(insert, delete, replace).
Given a string S of length N, find the minimum number of characters to insert at any position to make the string a palindrome.
Approach: Find the Longest Palindromic Subsequence (LPS) of S, which equals LCS(S, reverse(S)). Answer = N - LPS.
Given N items each with a weight and value, and a knapsack with capacity W, find the maximum total value of items you can carry. Each item can be included at most once.
Approach: 2D DP: dp[i][w] = max value using first i items with capacity w. Either skip item i or include it (if weight[i] ≤ w).
Given an even-length array A of N elements, choose at most N/2 elements (not necessarily consecutive). Maximise the XOR of the selected elements. Print the maximum XOR value.
Approach: Build a linear XOR basis (Gaussian elimination over GF(2)). The basis can represent any XOR from the array; since we can pick any subset of the basis (which has size ≤ N), the N/2 constraint is usually non-binding — always try max XOR from basis.
Given an array A of N integers, choose a non-negative integer B. Set A[i] = A[i] XOR B for all i. Minimise the number of inversions in the resulting array A. Print the minimum inversion count modulo 10⁹+7.
Approach: For each bit position independently, decide whether flipping that bit reduces inversions. Use a trie to count inversions bit-by-bit. Count cross-inversions for each candidate bit of B greedily from MSB to LSB.
You have N gifts of different types (given as array where A[i] is the type of gift i). Pack them into exactly K boxes (consecutive subarrays — each gift in exactly one box). The value of a box equals the number of distinct gift types inside it. Maximise the total value across all K boxes.
Approach: DP with sliding window + HashMap. dp[k][i] = max value packing first i gifts into k boxes. Use prefix sum of distinct counts and contribution tracking to speed up transitions.
N heroes and M villains are positioned on a number line. A hero at position h can defeat a villain at position v if |h - v| ≤ K. Find the maximum number of villain-hero pairs (one hero defeats at most one villain, one villain defeated by at most one hero).
Approach: Sort both arrays. Use two pointers — match earliest available hero with the nearest reachable villain. Greedy pairing with prefix sum for counting.
Given a binary string S of length N, its "ugliness" is the decimal value it represents. You can perform two operations with a total budget of CASH coins: (1) Swap the leftmost '1' with a '0' to its right — costs A coins. (2) Flip a character (0→1 or 1→0) — costs B coins. Minimise the ugliness.
Approach: Greedy — try to minimise the most significant bits. Decide for each leading 1: is it cheaper to swap it left or flip it to 0, given remaining budget? Process left to right.
Given N road segments, each with a terrain difficulty level, and a budget of K operations (each operation reduces one segment's difficulty by 1), minimise the maximum difficulty across all segments after operations.
Approach: Binary search on the answer (candidate maximum difficulty X). For each X, greedily compute total operations needed to bring all segments to ≤ X. Find smallest X where ops needed ≤ K.
Given an array A of N integers, find the minimum number of element changes needed to make it a "mountain array" — an array that first strictly increases to a peak and then strictly decreases (peak not at either end).
Approach: For each index i as the peak candidate, compute LIS ending at i from the left and LDS starting at i to the right. Elements to keep = LIS_left[i] + LDS_right[i] - 1. Min changes = N - max of this over all valid peaks.
💡 Infosys Coding Round — Exam Tips & Pattern Analysis (2021–2026)
- Format is fixed at 3 questions: Easy (20 pts) + Medium (30 pts) + Hard (50 pts) in 3 hours for DSE/SP. Solving Easy fully + Medium partially (80% test cases) is enough to clear the cutoff in most years.
- Arrays & Strings dominate Easy: Reverse, rotate, palindrome, anagram, missing number — these appear almost every cycle. Master them first.
- Greedy is the Medium pattern: Most Q2s involve sorting + greedy decisions (activity selection, profit maximisation, segment split). Learn to identify greedy problems quickly.
- DP is essential for Hard: Knapsack, LIS, Edit Distance, Coin Change, and Word Break appear repeatedly in SP/DSE Q3 from 2021–2026. Know at least 5 DP patterns cold.
- Bit Manipulation is SP-specific: XOR-based questions (Max XOR subset, Xor-Sum, inversion minimisation via XOR) appear almost exclusively in SP / HackWithInfy from 2022 onward.
- Partial scoring matters: Infosys scores by test cases passed. Write a brute-force that handles small inputs, then optimise — partial marks for Easy/Medium can still clear the cut.
- Language: Java and Python are safe. C++ is faster but error-prone with memory; Python's readable but may TLE on Hard problems. Choose what you can debug fastest.
- HackWithInfy Round 2 goes beyond this list — expect Codeforces 2200–2600 level problems. Competitive programming practice is necessary for SP final rounds.
- Edge cases always tested: Empty arrays, single elements, all identical values, maximum N constraints. Always code defensively.
- Time allocation: Spend max 20 min on Easy, 45 min on Medium, rest on Hard. Submit and revisit — don't get stuck.