Top 50 Infosys Coding Questions 2021–2026 | SE, DSE & SP Roles | PYQ Easy Medium Hard
🔥 PYQ 2021 – 2026 · Candidate-Verified

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.

📋 50 Questions 🎯 SE · DSE · SP 📅 2021 – 2026 ⚡ Easy · Medium · Hard 🏆 HackWithInfy Included

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.

RoleQuestionsDurationEasy TopicMedium TopicHard Topic
SE290 minArrays / StringsGreedy / Sorting
DSE33 hrsDS BasicsGreedy / DPDP / Graphs
SP (HackWithInfy)33 hrsSimulation / ArraysGreedy + Bit ManipDP / XOR / Graphs
🟢 Easy — SE / DSE / SP Q1

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).

1
Reverse an Array
EasySE · DSE2021–24

Given an array of N integers, reverse it in-place and print the result.

Input:N=5, A=[1, 2, 3, 4, 5]Output:[5, 4, 3, 2, 1]

Approach: Two-pointer — swap A[left] and A[right], move pointers inward until they cross.

⏱ O(n)🗂 O(1)
2
Check Palindrome String
EasySE · DSE · SP2021–26

Given a string S, determine whether it reads the same forwards and backwards (palindrome). Ignore case.

Input:"racecar"Output:YESr-a-c-e-c-a-r reversed = racecar ✓
Input:"hello"Output:NO

Approach: Compare S with its reverse; or use two pointers from both ends.

⏱ O(n)🗂 O(1)
3
Second Largest Element in an Array
EasySE · DSE2022–25

Find the second largest distinct element in an array of N integers. If no such element exists, return -1.

Input:N=6, A=[12, 35, 1, 10, 34, 1]Output:34Largest=35, Second largest=34

Approach: Single pass — maintain two variables: first and second. Update both as you iterate.

⏱ O(n)🗂 O(1)
4
Count Vowels and Consonants in a String
EasySE2021–23

Given a string, count the number of vowels (a, e, i, o, u — case insensitive) and consonants separately.

Input:"Hello World"Output:Vowels: 3, Consonants: 7Vowels: e, o, o | Consonants: H, l, l, W, r, l, d

Approach: Iterate each character; skip spaces; check against vowel set for classification.

⏱ O(n)🗂 O(1)
5
Find the Missing Number (1 to N)
EasySE · DSE2021–26

An array contains N-1 distinct integers in the range [1, N]. Exactly one number is missing. Find it.

Input:N=6, A=[1, 2, 4, 5, 6]Output:3Expected sum = 6×7/2 = 21; Actual sum = 18; Missing = 3

Approach: Compute expected sum = N*(N+1)/2 and subtract array sum. Or use XOR.

⏱ O(n)🗂 O(1)
6
Check if a Number is Prime
EasySE · DSE2021–25

Given an integer N (N ≥ 2), determine whether it is a prime number.

Input:17Output:PrimeDivisible only by 1 and 17
Input:12Output:Not Prime12 = 2 × 6

Approach: Check divisibility from 2 to √N. If any divisor found → not prime.

⏱ O(√n)🗂 O(1)
7
Print Fibonacci Series up to N Terms
EasySE2021–23

Given N, print the first N terms of the Fibonacci sequence.

Input:N=7Output:0 1 1 2 3 5 8

Approach: Use two variables a=0, b=1; print a, then update a,b iteratively N times.

⏱ O(n)🗂 O(1)
8
Binary Search in a Sorted Array
EasySE · DSE2022–25

Given a sorted array A of N integers and a target T, return the index of T in A. If not found, return -1.

Input:A=[2, 5, 8, 12, 16, 23], T=12Output:3A[3] = 12

Approach: Maintain low and high pointers; check mid; halve the search space each iteration.

⏱ O(log n)🗂 O(1)
9
Reverse a Singly Linked List
EasySE · DSE2021–26

Given the head of a singly linked list, reverse it in-place and return the new head.

Input:1 → 2 → 3 → 4 → 5 → NULLOutput:5 → 4 → 3 → 2 → 1 → NULL

Approach: Use three pointers: prev=NULL, curr=head, next. Reverse curr.next = prev and advance.

⏱ O(n)🗂 O(1)
10
Check if Two Strings are Anagrams
EasySE · DSE2021–25

Given two strings S and T, determine if they are anagrams of each other (same characters, same frequency, different order).

Input:S="listen", T="silent"Output:YES
Input:S="hello", T="world"Output:NO

Approach: Sort both strings and compare, or use a frequency HashMap (count up for S, count down for T).

⏱ O(n log n)🗂 O(1)
11
Find All Duplicates in an Array
EasySE · DSE2022–24

Given an array of N integers where elements are in range [1, N], find all elements that appear more than once.

Input:N=8, A=[4, 3, 2, 7, 8, 2, 3, 1]Output:[2, 3]

Approach: For each A[i], negate A[abs(A[i])-1]. If it's already negative, that index+1 is a duplicate.

⏱ O(n)🗂 O(1)
12
Rotate Array by K Steps to the Right
EasySE · DSE2021–25

Given an array A of N integers and an integer K, rotate the array to the right by K steps.

Input:A=[1,2,3,4,5,6,7], K=3Output:[5,6,7,1,2,3,4]

Approach: Reverse whole array → reverse first K → reverse remaining N-K. Effective K = K % N.

⏱ O(n)🗂 O(1)
13
Sum of Both Diagonals of a Matrix
EasySE · DSE2022–24

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.

Input:[[1,2,3],[4,5,6],[7,8,9]]Output:25Primary: 1+5+9=15 | Secondary: 3+5+7=15 | Centre 5 counted once → 25

Approach: Single pass — add A[i][i] and A[i][N-1-i]; subtract A[N/2][N/2] once when N is odd.

⏱ O(n)🗂 O(1)
14
Implement Bubble Sort
EasySE2021–23

Sort an array of N integers in ascending order using Bubble Sort. Print the sorted array.

Input:N=5, A=[64, 34, 25, 12, 22]Output:[12, 22, 25, 34, 64]

Approach: Repeatedly swap adjacent elements if out of order. Optimise with a swapped flag to exit early if already sorted.

⏱ O(n²) worst🗂 O(1)
15
Check if a Number is a Power of 2
EasySE · DSE2022–25

Given a positive integer N, determine if it is a power of 2.

Input:16Output:YES16 = 2⁴
Input:18Output:NO

Approach: Use bit trick: N > 0 && (N & (N-1)) == 0. Powers of 2 have exactly one set bit.

⏱ O(1)🗂 O(1)
16
Remove One Digit to Make Number Maximum
EasyDSE · SP2023–26

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.

Input:number="23551", d=5Output:"2351"Removing the first 5 gives 2351; removing the second gives 2351 — same here; always remove the leftmost occurrence that gives max result
Input:number="9591", d=9Output:"591"

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.

⏱ O(n)🗂 O(n)
17
Count Repeated and Non-Repeated Elements
EasyDSE · SP2023–26

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.

Input:N=6, A=[1, 2, 2, 3, 3, 3]Output:Repeated: 2, Non-Repeated: 12 and 3 appear more than once (count=2); 1 appears once (count=1)

Approach: Build a frequency HashMap; scan entries — count those with freq > 1 as repeated, freq == 1 as non-repeated.

⏱ O(n)🗂 O(n)
18
Zigzag (Spiral) Level-Order Traversal of Binary Tree
Easy–MedSE · DSE2022–25

Given the root of a binary tree, return its zigzag level-order traversal (alternate left-to-right and right-to-left per level).

Input Tree: 3 / \ 9 20 / \ 15 7Output:[[3], [20, 9], [15, 7]]Level 0: left→right | Level 1: right→left | Level 2: left→right

Approach: BFS with a deque; toggle a direction flag per level to decide whether to append front or back.

⏱ O(n)🗂 O(n)
19
Smallest Power of 2 Greater Than or Equal to N
EasyDSE · SP2023–26

Given an array A of N integers, for each element find the smallest power of 2 that is ≥ that element.

Input:A=[3, 7, 1, 10]Output:[4, 8, 1, 16]For 3→4(2²), 7→8(2³), 1→1(2⁰), 10→16(2⁴)

Approach: For each value, if already a power of 2 return it. Otherwise find MSB position and return 2^(position+1).

⏱ O(n·log max_val)🗂 O(1)
20
First Non-Repeating Character in a String
EasySE · DSE2021–25

Given a string S, find the first character that does not repeat. Return the character; if none, return '#'.

Input:"geeksforgeeks"Output:'f'g, e, k, s all repeat; 'f' is the first non-repeating character

Approach: Build a frequency array (size 26) in one pass; scan string again and return the first character with freq=1.

⏱ O(n)🗂 O(1)
🟠 Medium — DSE Q2 / SP Q2

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.

21
Longest Substring Without Repeating Characters
MediumDSE · SP2021–26

Given a string S, find the length of the longest substring with all unique characters.

Input:"abcabcbb"Output:3Longest window with no repeat: "abc" (length 3)
Input:"pwwkew"Output:3"wke"

Approach: Sliding window + HashMap. Move right pointer; if duplicate found, move left pointer past the previous occurrence.

⏱ O(n)🗂 O(min(n,m))
22
Next Permutation
MediumDSE · SP2022–25

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.

Input:[1, 2, 3]Output:[1, 3, 2]
Input:[3, 2, 1]Output:[1, 2, 3]

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.

⏱ O(n)🗂 O(1)
23
Detect a Loop in a Linked List
MediumSE · DSE2021–25

Given a linked list, detect whether it contains a cycle. Return true if a cycle exists, false otherwise.

Input:1 → 2 → 3 → 4 → 5 → (back to 2)Output:true

Approach: Floyd's Cycle Detection — use two pointers (slow moves 1 step, fast moves 2). If they meet, a cycle exists.

⏱ O(n)🗂 O(1)
24
Maximum Product Subarray
MediumDSE · SP2022–26

Given an integer array A, find the contiguous subarray that has the largest product and return that product.

Input:A=[2, 3, -2, 4]Output:6Subarray [2,3] has product 6
Input:A=[-2, 0, -1]Output:0

Approach: Track both max and min product at each position (min can turn max after multiplying a negative). Update global max each step.

⏱ O(n)🗂 O(1)
25
Valid Parentheses / Balanced Brackets
MediumSE · DSE · SP2021–26

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.

Input:"({[]})"Output:Valid
Input:"([)]"Output:Invalid

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.

⏱ O(n)🗂 O(n)
26
Longest Palindromic Substring
MediumSE · DSE · SP2021–26

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.

Input:"ababc"Output:"aba"Both "aba" and "bab" have length 3; "aba" starts at index 0 (smaller)
Input:"babad"Output:"bab"

Approach: Expand-around-centre for each character (both odd and even lengths). Track the longest found. DP table also works in O(n²).

⏱ O(n²)🗂 O(1)
27
Merge Intervals
MediumDSE · SP2022–25

Given a list of intervals [start, end], merge all overlapping intervals and return a list of non-overlapping intervals.

Input:[[1,3],[2,6],[8,10],[15,18]]Output:[[1,6],[8,10],[15,18]][1,3] and [2,6] overlap → merged to [1,6]

Approach: Sort by start time. Iterate — if current interval overlaps the last merged one, extend end; otherwise push to result.

⏱ O(n log n)🗂 O(n)
28
Longest Increasing Subsequence (LIS)
MediumDSE · SP2021–26

Given an array of N integers, find the length of the longest strictly increasing subsequence.

Input:A=[10, 9, 2, 5, 3, 7, 101, 18]Output:4LIS: [2, 3, 7, 101] or [2, 5, 7, 101]

Approach: Patience sorting — maintain a tails array; binary search to find the position to replace. Length of tails array = LIS length.

⏱ O(n log n)🗂 O(n)
29
Word Break Problem
MediumDSE · SP2022–25

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.

Input:S="leetcode", dict=["leet","code"]Output:true"leet" + "code"
Input:S="catsandog", dict=["cats","dog","sand","and","cat"]Output:false

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.

⏱ O(n²)🗂 O(n)
30
Reverse a Stack Using Recursion
MediumSE · DSE2022–26

Given a stack, reverse it using only recursion — no loops or extra data structures allowed.

Input:Stack = [1, 2, 3, 4, 5] (5 on top)Output:Stack = [5, 4, 3, 2, 1] (1 on top)

Approach: Pop all elements recursively to the call stack, then use a helper insertAtBottom() to reinsert them — effectively reversing the order.

⏱ O(n²)🗂 O(n) call stack
31
Subset Sum Problem
MediumDSE · SP2021–25

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.

Input:A=[3, 34, 4, 12, 5, 2], S=9Output:trueSubset {4, 5} sums to 9
Input:A=[3, 34, 4, 12, 5, 2], S=30Output:false

Approach: DP table dp[i][j] = true if subset of A[0..i-1] sums to j. Build bottom-up.

⏱ O(n·S)🗂 O(n·S)
32
Check if a Linked List is a Palindrome
MediumSE · DSE2021–24

Given the head of a singly linked list, determine whether it reads the same forwards and backwards.

Input:1 → 2 → 2 → 1Output:true
Input:1 → 2 → 3Output:false

Approach: Find mid with slow/fast pointers → reverse second half → compare with first half → restore (optional).

⏱ O(n)🗂 O(1)
33
Combination Sum (Unique Combinations)
MediumDSE · SP2022–25

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.

Input:candidates=[2,3,6,7], target=7Output:[[2,2,3],[7]]

Approach: Backtracking — for each candidate, recurse with remaining target; include same candidate again (unbounded). Prune when remaining < 0.

⏱ O(2^target)🗂 O(target)
34
Implement a Trie (Prefix Tree)
MediumDSE · SP2022–25

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.

Operations:insert("apple") → search("apple") → true
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.

⏱ O(L) per op🗂 O(alphabet × L × N)
35
LRU Cache Implementation
MediumDSE · SP2021–24

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.

Operations (capacity=2):put(1,1) → put(2,2) → get(1)→1 → put(3,3) (evicts 2) → get(2)→-1 → put(4,4) (evicts 1) → get(1)→-1 → get(3)→3 → get(4)→4

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.

⏱ O(1) per op🗂 O(capacity)
🔴 Hard — DSE Q3 / SP Q2–Q3 / HackWithInfy

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.

36
RPG Monster Defeat (Greedy Sorting)
HardSP · HackWithInfy2021–23

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.

Input:N=3, e=5, power=[3,7,2], bonus=[4,3,5]Output:3Kill monster 2 (need 2, gain 5, e=10), kill monster 0 (need 3, gain 4, e=14), kill monster 1 (need 7, e≥7 ✓)

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.

⏱ O(n log n)🗂 O(1)
37
Xor-Sum Maximization
HardSP · HackWithInfy2022–24

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.

Input:N=3, K=8, A=[1, 2, 3]Output:14 (for x=4: (4^1)+(4^2)+(4^3) = 5+6+7 = 18 — check all x in [0,8])
Note on example:Xor_sum(8)=(8^7)+(8^4)+(8^0)+(8^3) = 46 in a different sample

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).

⏱ O(n·log K)🗂 O(1)
38
LIS with Bitwise Operation Condition
HardSP · HackWithInfy2023–26

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.

Input:N=4, A=[1,3,2,4], OP=AND, target=0Output:3Subsequence [1,2,4]: 1&2=0✓, 2&4=0✓ — length 3

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).

⏱ O(n²)🗂 O(n)
39
Split Array into K Consecutive Segments — Minimum Cost
HardSP2022–24

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.)

Input (minimize max segment sum):N=5, K=3, A=[7,2,5,10,8]Output:14Splits: [7,2,5],[10],[8] → max=14. Optimal.

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.

⏱ O(n log(sum))🗂 O(1)
40
Coin Change — Minimum Number of Coins (Unbounded)
HardDSE · SP2021–26

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.

Input:coins=[1,5,6,9], amount=11Output:25+6=11 (2 coins). Greedy gives 9+1+1=3 — DP beats greedy here.
Input:coins=[2], amount=3Output:-1

Approach: DP. dp[i] = min coins for amount i. For each coin, dp[i] = min(dp[i], dp[i-coin]+1).

⏱ O(amount × coins)🗂 O(amount)
41
Edit Distance (Levenshtein Distance)
HardDSE · SP2022–25

Given two strings S and T, find the minimum number of single-character edit operations (insert, delete, replace) required to convert S into T.

Input:S="horse", T="ros"Output:3horse→rorse(replace h/r)→rose(delete r)→ros(delete e) = 3 ops
Input:S="intention", T="execution"Output:5

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).

⏱ O(m·n)🗂 O(m·n)
42
Minimum Insertions to Make a String Palindrome
HardDSE · SP2022–26

Given a string S of length N, find the minimum number of characters to insert at any position to make the string a palindrome.

Input:"abcd"Output:3Insert "dcb" → "dcbabcd" is a palindrome. Min insertions = n - LPS length
Input:"aab"Output:1Insert 'b' → "baab"

Approach: Find the Longest Palindromic Subsequence (LPS) of S, which equals LCS(S, reverse(S)). Answer = N - LPS.

⏱ O(n²)🗂 O(n²)
43
0/1 Knapsack Problem
HardDSE · SP2021–26

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.

Input:N=3, W=4, weights=[4,5,1], values=[1,2,3]Output:3Take item 3 (weight=1, value=3); remaining capacity 3 — no other item fits beneficially.
Input:N=4, W=5, weights=[2,3,4,5], values=[3,4,5,6]Output:7Items 1+2: weight=5, value=7

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).

⏱ O(n·W)🗂 O(n·W)
44
Maximum XOR of a Subset with at Most N/2 Elements
HardSP · HackWithInfy2021–25

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.

Input:N=4, A=[1, 2, 4, 7]Output:7Choose subset {7} — XOR=7. Size=1 ≤ N/2=2.
Input:N=4, A=[2, 4, 6, 8]Output:14Choose {2,4,8} — XOR=2^4^8=14. Size=3 > N/2 — try {4,8}=12, {2,8}=10, {2,4}=6, {6,8}=14 ✓

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.

⏱ O(n·30)🗂 O(30)
45
Minimum Inversions After XOR-ing with B
HardSP · HackWithInfy2022–25

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.

Input:N=3, A=[3, 1, 2]Output:0Choose B=3: A becomes [0,2,1]? Try different B values to minimise inversions.

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.

⏱ O(n·30)🗂 O(n·30)
46
Gift Packing — Maximise Value Across K Boxes
HardSP · HackWithInfy2023–25

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.

Input:N=6, K=3, A=[1,1,2,2,3,3]Output:4Optimal split: [1,1,2]=2, [2]=1, [3,3]=1 → total=4. Or [1]=1,[1,2,2]=2,[3,3]=1 → 4.

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.

⏱ O(K·n·n) → optimised O(K·n)🗂 O(K·n)
47
Heroes vs Villains Battle (Prefix Sum + Greedy)
HardSP · HackWithInfy2022–24

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).

Input:N=3, M=3, K=2, heroes=[1,5,9], villains=[3,6,11]Output:2Hero at 1 defeats villain at 3 (|1-3|=2 ≤ 2). Hero at 5 defeats villain at 6 (|5-6|=1 ≤ 2). Villain at 11 undefeated.

Approach: Sort both arrays. Use two pointers — match earliest available hero with the nearest reachable villain. Greedy pairing with prefix sum for counting.

⏱ O((N+M) log(N+M))🗂 O(1)
48
Ugliness Minimization (Greedy + Bit Manipulation)
HardSP · HackWithInfy2023–25

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.

Input:S="011111", CASH=7, A=1, B=3Output:7 (binary "000111")Swap 0 with leftmost 1 (cost 1, CASH=6): "011111" → after ops → "000111"=7

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.

⏱ O(n²) worst🗂 O(n)
49
Road Terrain Transformation (Binary Search + Greedy)
HardSP · HackWithInfy2023–26

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.

Input:N=5, K=3, difficulties=[3,5,2,8,4]Output:5Target max=5: segment with 8 needs 3 reductions, costing exactly K=3. Feasible.

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.

⏱ O(n log(max_diff))🗂 O(1)
50
Mountain Array Transformation (Greedy + Two Pointers)
HardSP · HackWithInfy2022–26

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).

Input:N=5, A=[2,1,4,5,3]Output:1Change A[1]=1 to 2 → [2,2,4,5,3] — still not mountain. Or change A[0]=2 to 0 → [0,1,4,5,3] — mountain ✓. Min changes=1.

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.

⏱ O(n log n)🗂 O(n)

💡 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.