← Infosys Interview Insights

Infosys·Software Engineer·Online Assessment (OA)·Junior

JuniorPrefer not to say
Aug 2026

Summary

Infosys OA with 4 coding problems in 3 hours. The questions ranged from medium to hard and from what I saw around me, finishing more than 2 was basically unheard of.

Questions Asked (4)

Q1

Given two equal-length strings S and T, find the minimum number of character replacements to make S an anagram of T. Replacing a vowel with a consonant (or vice versa) costs 1, while swapping within the same category (vowel to vowel, consonant to consonant) costs 2. Characters already balanced across both strings cost nothing.

Algorithms & Data Structures
Author's notes

This one felt manageable at first.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by computing the character frequency difference between S and T to identify which characters are in surplus and which are in deficit. Then categorize the surplus characters into vowels and consonants, and greedily match cross-category replacements (cost 1) before handling same-category replacements (cost 2). This greedy approach minimizes total cost by always preferring cheaper operations first.

Pro tip: Explicitly mention that cross-category swaps (vowel ↔ consonant) should always be prioritized over same-category swaps because they resolve two imbalances at once for a lower cost — this demonstrates you understand the greedy optimality argument, which interviewers at Infosys look for in algorithm design questions.

1. Compute Character Frequency Differences

Build frequency maps for both S and T, then compute the net surplus/deficit for each character (freq[S][c] - freq[T][c]). Positive values indicate characters S has in excess; negative values indicate characters S needs more of.

2. Separate Surplus by Category

Partition the surplus characters (those with positive difference) into two buckets: surplus vowels and surplus consonants. Similarly, partition the deficit characters into deficit vowels and deficit consonants.

3. Apply Cross-Category Replacements (Cost 1)

Match surplus vowels against deficit consonants, and surplus consonants against deficit vowels. Each such pairing costs 1 and resolves one unit of imbalance on each side — apply as many of these as possible first.

4. Apply Same-Category Replacements (Cost 2)

Handle any remaining surplus vowels paired with deficit vowels, and remaining surplus consonants paired with deficit consonants. Each such replacement costs 2 since it stays within the same character category.

5. Sum and Return Total Cost

Accumulate the costs from both phases and return the total. Verify your solution with edge cases such as strings that are already anagrams (cost 0) or strings composed entirely of vowels or consonants.

Key Points to Mention

  • Frequency difference map: only characters with non-zero net difference need to be addressed, making the problem tractable in O(n) time.
  • Greedy optimality: cross-category replacements (cost 1) are always preferred because they simultaneously fix a surplus and a deficit more cheaply than same-category swaps (cost 2).
  • Vowel set definition: clearly define the vowel set {a, e, i, o, u} and treat all other alphabetic characters as consonants to avoid ambiguity.
  • Balanced characters cost nothing: characters whose counts are equal across S and T require no action, so the algorithm only processes the imbalance, not the entire string.
  • Time and space complexity: the algorithm runs in O(n) time for frequency counting and O(1) space (since the alphabet is fixed at 26 characters), making it highly efficient.
  • Edge cases: handle already-anagram inputs (output 0), all-vowel or all-consonant strings, and single-character strings to demonstrate thoroughness.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q2

A modified house robber problem where you cannot rob adjacent houses, and additionally, any two consecutively robbed houses must have profits differing by at least D in absolute value. Maximize total profit.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

Classic house robber DP breaks down here because the extra constraint makes transitions O(n²) and that's too slow.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Treat this as a dynamic programming problem where the state must track both the current house index and the last robbed house index (or its profit value) to enforce both the adjacency and profit-difference constraints. Define dp[i][j] as the maximum profit when considering house i with house j being the most recently robbed house, then build transitions carefully. Clearly articulate the state space, transition logic, and how the two constraints interact before coding.

Pro tip: Explicitly call out the state space complexity trade-off: tracking the last robbed house index gives O(n²) states which is manageable, but naively tracking profit values could explode — showing you reason about scalability signals strong engineering maturity to interviewers.

1. Clarify Constraints & Examples

Confirm input size, whether profits can be negative, and what D represents. Walk through a small example (e.g., [2, 7, 9, 3, 1], D=3) to validate your understanding of both constraints before designing a solution.

2. Define the DP State

Define dp[i][j] as the maximum profit achievable up to house i where house j was the last robbed house (j < i). This two-dimensional state captures both which house we are at and what the last robbed profit was, enabling enforcement of the |profit[i] - profit[j]| >= D constraint.

3. Formulate Transitions

For each house i and each valid previous house j (where i - j >= 2 and |profit[i] - profit[j]| >= D), set dp[i][j] = max(dp[i][j], dp[j][k] + profit[i]) for all valid k. Also handle the base case where house i is the first house robbed: dp[i][-1] = profit[i].

4. Analyze Complexity & Optimize

Identify that the naive approach is O(n³) time and O(n²) space, then discuss whether sorting or pruning can reduce constant factors. Mention that for large n, segment trees or sorted structures could optimize the inner lookup, demonstrating awareness of scalability.

5. Code, Test & Edge Cases

Implement the solution cleanly, then test against edge cases: all houses skipped (answer is 0 or best single house), D=0 (reduces to classic house robber), negative profits, and arrays of size 1 or 2. Verbally trace through your example to verify correctness.

Key Points to Mention

  • Two-dimensional DP state (current index + last robbed index) to simultaneously enforce both constraints
  • Adjacency constraint: i - j >= 2, ensuring no two consecutive houses are robbed
  • Profit-difference constraint: |profit[i] - profit[j]| >= D as an additional transition guard
  • Base case handling: robbing a house as the very first robbery (no previous house constraint)
  • Time complexity O(n³) for naive DP and potential optimizations using sorted structures to O(n² log n)
  • Edge cases: D=0 reduces to classic house robber, single-element arrays, and all-negative profit arrays

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q3

Partition an array into contiguous groups of at least 3 elements each. The profit from each group is its third-smallest value. Maximize the total profit across all groups, or return -1 if no valid partition exists.

Algorithms & Data Structures
Author's notes

Hardest one for me.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Recognize this as a dynamic programming problem where you build up an optimal solution by deciding where to place partition boundaries. Define dp[i] as the maximum profit achievable from the first i elements, then for each position i, try all valid group endings (groups of size >= 3) and use the third-smallest element of that group as the profit contribution. Sort each candidate group or use a selection algorithm to efficiently find the third-smallest value.

Pro tip: Mention that pre-sorting subarrays naively leads to O(n³ log n) complexity, but you can optimize by maintaining a running sorted structure or noting that for a fixed right boundary you can incrementally track the third-smallest as you extend the group leftward, bringing it closer to O(n²) — this shows you think beyond brute force.

1. Clarify Constraints & Edge Cases

Ask about array size, value ranges, and confirm what 'third-smallest' means for groups of exactly 3 (it's the maximum of the group). Identify the base case: if the array has fewer than 3 elements, return -1 immediately.

2. Define the DP State

Let dp[i] represent the maximum total profit using the first i elements with a valid partition, initialized to -infinity (invalid). dp[0] = 0 as the base case (empty array, zero profit).

3. Transition: Enumerate Valid Groups

For each index i (1-indexed), iterate over all starting points j such that the group [j..i] has at least 3 elements. If dp[j-1] is valid, compute the third-smallest of the subarray and update dp[i] = max(dp[i], dp[j-1] + third_smallest(j, i)).

4. Efficiently Find Third-Smallest

As you extend the left boundary j leftward from i, maintain a sorted structure (e.g., insertion into a sorted list or a max-heap of size 3) to track the third-smallest incrementally, avoiding a full sort for each subarray.

5. Return Result & Analyze Complexity

Return dp[n] if it's valid (not -infinity), otherwise return -1. Discuss time complexity: O(n²) for the DP transitions with O(n log n) for sorting per transition in the naive case, and how incremental tracking improves this.

Key Points to Mention

  • Dynamic programming formulation with dp[i] = max profit for first i elements
  • Third-smallest element selection — for a group of size k >= 3, it's the element at index 2 in the sorted group
  • Incremental/sliding approach to avoid recomputing third-smallest from scratch for each subarray
  • Validity tracking — propagating -1 (invalid state) when no valid partition exists up to position i
  • Edge cases: array length < 3 returns -1, and groups where all elements are equal (third-smallest equals all values)
  • Trade-off between brute force O(n³ log n) and optimized O(n²) DP with incremental order statistics

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q4

Find the minimum cost path from a start city to a destination in an undirected graph where each node has a visit cost. You have one optional VIP pass: using it on a city makes that city free but doubles the cost of the next city visited. Total cost includes start and end cities.

Algorithms & Data StructuresSystem Design
Author's notes

Dijkstra with extended state, basically.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model this as a modified Dijkstra's shortest path problem where the state includes not just the current city but also whether the VIP pass has been used and whether the next city's cost should be doubled. Extend the state space to (city, vip_used, next_doubled) and run Dijkstra over this augmented graph to find the globally optimal cost. This cleanly handles the pass's side effect without requiring exhaustive search.

Pro tip: Explicitly call out that the VIP pass introduces a 'state dependency' between consecutive nodes — this is the crux of the problem and shows you recognize it's not a vanilla shortest path problem. Mentioning that naive greedy application of the pass on the most expensive city can be suboptimal (due to the doubling penalty) will impress the interviewer.

1. Clarify the Problem Constraints

Confirm key details: is the graph weighted by node visit costs only (no edge weights), can the VIP pass be used on the start or end city, and is the graph connected? Clarifying these prevents wasted effort on wrong assumptions.

2. Define the Augmented State Space

Represent each state as a tuple (current_city, vip_used: bool, next_cost_doubled: bool) to capture all relevant information at any point in the traversal. This transforms the problem into a standard shortest path on a larger but well-defined state graph.

3. Model State Transitions and Costs

For each state, enumerate transitions: moving to a neighbor without using the pass, or using the pass on the current city (making it free but flagging the next city for double cost). Carefully compute the cost of entering each neighbor based on the 'next_cost_doubled' flag.

4. Run Dijkstra on the Augmented Graph

Apply Dijkstra's algorithm using a min-heap over the augmented states, initializing with the start city's cost (considering pass usage options). Track visited states to avoid reprocessing and extract the minimum cost when the destination is reached.

5. Analyze Complexity and Edge Cases

State space is O(N × 2 × 2) = O(N), so overall complexity is O(N log N) with a binary heap, which is efficient. Discuss edge cases: using the pass on the last city (no doubling penalty applies), using it on the start city, and graphs with a single node.

Key Points to Mention

  • State augmentation: extending Dijkstra's state to include VIP pass usage and the 'next city doubled' flag to handle inter-node dependencies
  • Why greedy pass application is insufficient: using the pass on the highest-cost city may be suboptimal if it doubles an even more expensive subsequent city
  • Correct cost computation: the start city's cost is included, the VIP pass makes the chosen city free, and the immediately following city's cost is multiplied by 2
  • Dijkstra's suitability: all effective edge costs are non-negative after modeling, making Dijkstra correct and efficient here
  • Time and space complexity: O(N log N) time and O(N) space due to the constant factor expansion of the state space
  • Edge cases: pass used on destination (no doubling side effect), pass unused (standard Dijkstra result), and disconnected graphs returning infinity or -1

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.