Skip to content

75. Sort Colors #51

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jul 17, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

The goal is to sort the array nums with elements representing the colors red (0), white (1), and blue (2) in one pass, using constant extra space.

Approach:

The most efficient way to solve this problem is by using the Dutch National Flag algorithm, which is a one-pass algorithm with constant extra space. The idea is to use three pointers:

  • low to track the position for the next 0 (red),
  • mid to traverse the array,
  • high to track the position for the next 2 (blue).

Algorithm:

  1. Initialize three pointers:

    • low at the start (0),
    • mid at the start (0),
    • high at the end (n-1) of the array.
  2. Traverse the array with mid:

    • If nums[mid] is 0 (red), …

Replies: 1 comment 2 replies

Comment options

mah-shamim
Aug 9, 2024
Maintainer Author

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 23, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants