LIMITED TIME 🎁: Register now to get 60 minutes of AI Mock Interviewing for FREE!

Join
    Infosys Interview Insights
    Infosys logo
    Infosys·Software Engineer·Online Assessment (OA)·Junior
    JuniorPrefer not to say
    Aug 2026
    3

    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)

    Algorithms & Data Structures
    A
    Author's notesFirst line only

    This one felt manageable at first.

    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.
    Algorithms & Data StructuresTechnical Trade-offs
    A
    Author's notesFirst line only

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

    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
    Algorithms & Data Structures
    A
    Author's notesFirst line only

    Hardest one for me.

    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
    Algorithms & Data StructuresSystem Design
    A
    Author's notesFirst line only

    Dijkstra with extended state, basically.

    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

    Discussion(3)

    Sign in to join the discussion.

    AH
    Alex H. Chen· 33d ago
    Q4Find 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.

    Your state definition is basically there. The state I'd use is (node, pass_used, is_doubled) where is_doubled means the current node's cost is doubled because the previous node used the VIP pass. Three binary flags, so 4 possible (pass_used, is_doubled) combinations per node. The cost to enter a node is node_cost * 2 if is_doubled, else node_cost. When you move to a neighbor without using the pass, is_doubled becomes false. When you use the pass on the current node (making it free) and move to a neighbor, that neighbor gets is_doubled = true and pass_used = true.

    One thing worth being careful about: "using the pass on a city makes that city free" means you're zeroing the current node's cost, not the next one. So the pass affects where you are now, and the doubling hits wherever you go next. Run Dijkstra over the (node, pass_used, is_doubled) state space with a priority queue on accumulated cost. Start state is (start, false, false) with cost = start_cost. The answer is the minimum cost across all states (destination, *, *). State space is O(4n) which is fine.

    Q
    QuestionsByK· 33d ago
    Q1Given 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.

    Your instinct on the greedy ordering is right. The key insight is that a vowel-consonant mismatch pair costs 1 to fix but eliminates two surplus characters simultaneously, so you want to exhaust those before touching same-category pairs. Concretely: compute frequency difference arrays for vowels and consonants separately, sum the absolute surpluses in each group, then pair cross-category surpluses first. Each cross pair costs 1 and reduces both surpluses by 1. Whatever same-category surplus remains after that costs 2 per pair.

    The implementation fumble you mentioned is almost always the same bug: people forget that the cross-category pairing quantity is min(vowel_surplus, consonant_surplus), not their sum. I made exactly that mistake on a similar problem and got a wrong answer on a case where one category had way more surplus than the other. The leftover from the larger group still needs same-category swaps at cost 2, and forgetting to add that in is where the count goes wrong. For an Infosys SWE OA under time pressure, getting the frequency counting right and handling that min() boundary cleanly is probably enough to clear whatever partial threshold they set.

    C
    CodeWithMaya· 33d ago
    Q3Partition 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.

    The third-smallest detail is actually the key insight that unlocks the DP. For any group of k elements (k >= 3), if you sort those elements, the third-smallest is index 2. Crucially, adding more elements to a group can only keep or lower the third-smallest value, never raise it. So you always want groups of exactly 3 if you're trying to maximize, because larger groups risk burying a high value further down the sorted order.

    That means the DP simplifies a lot: dp[i] = best profit partitioning the first i elements, and you only really need to consider groups of size 3, 4, maybe a few more depending on remainder constraints. For each position i, try group sizes g from 3 up to some limit, take the subarray ending at i of length g, find its third-smallest, add dp[i-g]. The "no valid partition" case is just when n < 3 or when no combination of group sizes >= 3 sums to n, which you can precheck.

    Finding the third-smallest for each candidate group efficiently: if you're iterating g from 3 upward for a fixed right endpoint, you can maintain a small sorted structure as you extend leftward. Or just accept O(g log g) per transition since g is bounded in practice. The remainder edge case (e.g., n=7 means you could do 3+4 or 4+3 but not 3+3+1) is worth handling explicitly before the main DP loop.

    Interview Details

    CompanyInfosys
    RoleSoftware Engineer
    RoundOnline Assessment (OA)
    LevelJunior
    OutcomePrefer not to say
    DateAug 2026

    Questions in this post

    Share your own experience

    Help the community by sharing what you went through.