Fewest Index Swaps to Make Two Replica Timelines Strictly Increasing

Last updated: November 29, 2026

Quick Overview

Two replicas logged sequence numbers into arrays A and B of equal length, and at any index you may swap A[i] with B[i]. Return the fewest swaps that make both arrays strictly increasing, given that it is always possible.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Two replicas logged sequence numbers into arrays A and B of equal length, and at any index you may swap A[i] with B[i]. Return the fewest swaps that make both arrays strictly increasing, given that it is always possible.

A Google onsite problem that tests two-state DP where the state is whether the current index was swapped. Interviewers look for a precise case analysis of the two compatibility conditions and an explanation of why both can hold at once.

What the Interviewer Expects
  • Define keep and swap states for each index
  • Write the two compatibility conditions between adjacent indices
  • Allow both transitions when both conditions hold
  • Use O(1) space
  • Trace a short example
Key Topics to Cover
1D dynamic programming
Two-state DP
Case analysis
Minimum swaps
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Swaps have different costs per index.
  • There are three arrays and you may permute the three values at each index.
  • Detect when it is impossible and return -1.
  • Make both arrays non-decreasing instead.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: lists A and B of equal length n, guaranteed solvable. Output the minimum number of indices to swap so both arrays become strictly increasing....

High-Level Design

Let keep be the fewest swaps for prefix 0..i with index i not swapped, and swap with index i swapped. Between i - 1 and i, two conditions matter. Condition 1: A[i-1] < A[i] and B[i-1] < B[i], so...


Submit Your Answer
Markdown supported