Uncrossed Lines solution explained

Uncrossed Lines puts two integer arrays on two parallel rows and asks for the most lines you can draw between equal values without any two lines crossing or sharing an endpoint. Lines that do not cross must connect positions in the same left-to-right order on both rows, so a valid set of lines is exactly a common subsequence, and the answer is the longest common subsequence of the two arrays. A two-row DP gives it in O(m × n) time and O(n) memory.

By Published 7 min read

The problem, restated

Write the values of the first array on a top line and the second array on a bottom line, each in its given order. You may draw a straight segment from a top value to a bottom value when they are equal. No two segments may cross, and each value can be the endpoint of at most one segment. Return the most segments you can draw.

Examples written for this page (outputs printed by the code below)
Top rowBottom rowMost linesOne choice
[4, 7, 2, 7][7, 4, 2, 7]34-4, 2-2, 7-7 (last ones)
[1, 2, 3][3, 2, 1]1Any single pair; two would cross
[5, 5][5]1The bottom 5 can take only one line
[1, 3, 5][2, 4]0No equal values
[2, 1, 2, 1][1, 2, 1, 2]31-1, 2-2, 1-1 or 2-2, 1-1, 2-2
Examples written for this page (outputs printed by the code below). Scroll sideways on a small screen.

What the interviewer is checking

Uncrossed Lines is a recognition test. The geometry is a disguise, and the interviewer wants to see you remove it: two lines cross exactly when their top endpoints and bottom endpoints are in opposite orders. Once you say that, the problem is LCS on integers and the code is familiar. Interviewers then check that you can justify the reduction, not just assert it, and some ask for the faster LIS-based method when values are distinct.

Questions to ask

  • Can one value have two lines? No, each endpoint is used at most once.
  • Do lines that touch at an endpoint count as crossing? Sharing endpoints is not allowed anyway, so only strict crossings matter.
  • How long are the arrays? A few thousand each is fine for the quadratic DP.

Brute force

Pick the shorter row and consider every subset of its positions. For each subset, check whether those values, in order, can be matched left to right somewhere in the other row; if they can, that many lines fit without crossing. The best subset size is the answer. With 2^k subsets for a row of length k, this only works for small rows, but it was the reference for this page's random tests, and it already hints at the reduction below: what you are choosing is an order-preserving match.

Why non-crossing lines are a common subsequence

Take two lines, one from top position i1 to bottom position j1 and one from i2 to j2, with i1 < i2. They cross when j1 > j2 and stay apart when j1 < j2. So a set of non-crossing lines, sorted by top position, also has increasing bottom positions. Reading the connected values in that order gives the same sequence on both rows: a common subsequence. In the other direction, any common subsequence picks increasing positions on both rows, and connecting them in order produces lines that never cross. The best line count and the LCS length are therefore equal.

Top-down DP

Think about the first value on each row. If they are equal, connecting them is always safe, and the rest is the same problem on the remaining values. If they differ, at least one of them gets no line, so drop either and keep the better result. Caching on the pair of starting positions gives O(m × n) states.

from functools import lru_cache

def max_uncrossed_memo(top, bottom):
    @lru_cache(maxsize=None)
    def lines(i, j):
        if i == len(top) or j == len(bottom):
            return 0
        if top[i] == bottom[j]:
            return 1 + lines(i + 1, j + 1)
        return max(lines(i + 1, j), lines(i, j + 1))

    return lines(0, 0)
Python: memoized recursion on start positions. O(m * n).

Recursion depth reaches m + n in the worst case, which runs into Python's default limit for arrays in the hundreds. Use it to explain the idea and the bottom-up version to submit.

Bottom-up with two rows

Fill a grid where cell (i, j) holds the answer for the first i top values and the first j bottom values. Each row only needs the row before it, so keep two arrays and swap them.

def max_uncrossed(top, bottom):
    prev = [0] * (len(bottom) + 1)
    for value in top:
        cur = [0] * (len(bottom) + 1)
        for j, other in enumerate(bottom, start=1):
            if value == other:
                cur[j] = prev[j - 1] + 1
            else:
                cur[j] = max(prev[j], cur[j - 1])
        prev = cur
    return prev[-1]
Python: previous row and current row. O(m * n) time, O(n) memory.
function maxUncrossedLines(top, bottom) {
  let prev = new Array(bottom.length + 1).fill(0);
  for (const value of top) {
    const cur = new Array(bottom.length + 1).fill(0);
    for (let j = 1; j <= bottom.length; j++) {
      cur[j] = value === bottom[j - 1]
        ? prev[j - 1] + 1
        : Math.max(prev[j], cur[j - 1]);
    }
    prev = cur;
  }
  return prev[bottom.length];
}
JavaScript: the same two-row fill.

When the bottom row has distinct values: LIS

If every value on the bottom row appears once, each top value can connect to at most one bottom position. Replace each top value with that position, skipping values that do not appear. Non-crossing lines then correspond to a strictly increasing subsequence of positions, so the answer is the length of the longest increasing subsequence, found with patience sorting and binary search in O(m log n).

from bisect import bisect_left

def max_uncrossed_distinct(top, bottom):
    where = {v: k for k, v in enumerate(bottom)}
    tails = []
    for value in top:
        if value not in where:
            continue
        pos = where[value]
        slot = bisect_left(tails, pos)
        if slot == len(tails):
            tails.append(pos)
        else:
            tails[slot] = pos
    return len(tails)
Python: LIS shortcut, valid only when bottom has no repeated values.

bisect_left keeps the subsequence strictly increasing, which matters when the top row repeats a value: two copies of the same value map to the same bottom position and must not both get a line to it.

Complexity

m values on top, n on the bottom
ApproachTimeExtra memory
Try every subset of one rowO(2^min(m, n) × (m + n))O(m + n)
Memoized recursionO(m × n)O(m × n)
Two-row DPO(m × n)O(n)
LIS shortcut (distinct bottom values)O(n + m log n)O(n)
m values on top, n on the bottom. Scroll sideways on a small screen.

Edge cases

  • Either array empty: 0 lines.
  • No shared values: 0.
  • Repeated values on one side only, which tests the one-line-per-endpoint rule.
  • Identical arrays: every position connects straight down, so the answer is the length.
  • Reversed arrays with distinct values: only one line fits.

Common mistakes

  • Counting shared values, or summing the minimum count of each value, which ignores crossings. [1, 2, 3] and [3, 2, 1] share three values but allow only one line.
  • Greedily connecting each top value to the first equal bottom value to the right of the last line. On [2, 1, 2] over [1, 2], the first 2 grabs the bottom 2 and nothing else fits, giving 1 line where 2 are possible.
  • Using the LIS shortcut when the bottom row has repeats. With [2, 1] over [2, 1, 2], the map keeps only one position for 2 and returns 1 instead of 2.
  • Using bisect_right in the LIS step, which lets two equal positions both count: [5, 5] over [5] would report 2 lines.
  • Off-by-one errors between array indexes and table indexes in the two-row fill.

How to explain it out loud

Fictional example

Removing the geometry
Candidate
Two lines cross exactly when their top ends and bottom ends are in opposite orders. So non-crossing lines, sorted by top position, have increasing bottom positions too, which means the connected values form a common subsequence of the two arrays.
Candidate
That makes this the longest common subsequence on integers. Same recurrence: match the fronts if equal, otherwise drop one side and take the better. Two rows of memory are enough.
Interviewer
Anything faster?
Candidate
If one array has distinct values, I can map the other array to positions in it and take the longest strictly increasing subsequence, which is m log n.

Stone Game II and Predict the Winner are table DPs where the state is a position plus something about the game. Shortest Common Supersequence turns the same LCS table into a constructed string. Longest Common Subsequence and Longest Increasing Subsequence cover the two building blocks this page uses.

Practicing with Natively

The win here is the one-sentence reduction, so practice saying it before touching code. A mock round on Mac or Windows with Natively transcribing lets you check later whether the reduction came first and was justified. After your own attempt, Natively can read the problem from a screenshot and suggest an approach, such as the LIS shortcut, to compare. Read more about the AI interview assistant.

Questions people ask

How do you solve Uncrossed Lines?

Compute the longest common subsequence of the two arrays: lines(i, j) = 1 + lines(i + 1, j + 1) when values match, otherwise max(lines(i + 1, j), lines(i, j + 1)). A two-row table does it in O(m times n).

Why is Uncrossed Lines the same as LCS?

Two lines cross exactly when their endpoints are in opposite orders, so non-crossing lines connect positions in the same order on both rows, which is a common subsequence.

What is the time complexity?

O(m times n) time and O(n) memory with two rows. If one array has distinct values, an LIS of mapped positions gives O(m log n).

Can I count shared values instead?

No. [1, 2, 3] and [3, 2, 1] share three values but allow only one line, because any two lines would cross.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP