QA
Intermediate LevelData Structures & Algorithms

How do you find the Longest Increasing Subsequence (LIS)?

ā“ Interview Prompt: Solve LIS using O(N²) DP and the O(N log N) patience sorting / binary search approach.

O(N²) DP:

dp[i] = LIS ending at index i.

dp[i] = 1 + max(dp[j]) for all j < i where nums[j] < nums[i].

O(N log N) — Patience Sorting / Binary Search:

Maintain a tails array where tails[i] = smallest tail element of all increasing subsequences of length i + 1.

•
For each num:
•
If num > tails.last → extend by 1 (append).
•
Else → binary search for the leftmost tail ≄ num and replace it.
•
LIS length = tails.length.

Code Implementation Example

typescript
// O(N log N) LIS via binary search on tails array
function lengthOfLIS(nums: number[]): number {
  const tails: number[] = [];

  for (const num of nums) {
    let lo = 0, hi = tails.length;
    while (lo < hi) {  // binary search: find first tail >= num
      const mid = (lo + hi) >> 1;
      if (tails[mid] < num) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = num; // replace or extend
  }
  return tails.length;
}

console.log(lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])); // 4 → [2,3,7,18]
šŸ’”O(N log N) LIS using patience sorting and binary search on tails array.
šŸŽÆ Interview Key Takeaway

LIS has a classic O(N²) DP and an elegant O(N log N) solution via binary search on a maintained tails array. Know both for interviews.

#DSA#LIS#Dynamic Programming#Binary Search#Intermediate
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?