Sort an Array of 0's, 1's, and 2's Problem Statement

Given an integer array ARR of size 'N' containing only the values 0, 1, and 2, the task is to sort this array.

The goal is to achieve the sorting in a single pass through the array.

Example:

Input:
T = 2
N = 5
ARR = [0, 2, 1, 2, 0]
N = 3
ARR = [0, 1, 0]
Output:
[0, 0, 1, 2, 2]
[0, 0, 1]
Note:

The solution must involve iterating over the array just once.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= (5 * 105)
  • 0 <= ARR[i] <= 2
  • You need to sort the given array/list itself. No need to return or print anything explicitly.
AnswerBot
4mo

Sort an array of 0's, 1's, and 2's in a single pass.

  • Use three pointers to keep track of 0's, 1's, and 2's positions while iterating through the array.

  • Swap elements based on the current element's value...read more

Help your peers!
Select
Add answer anonymously...

Top Software Engineer Interview Questions Asked at Capgemini Engineering

Q. What is a database management system?
Q. Explain the principles of Object-Oriented Programming (OOP).
Q. Given an array of characters, find the first non-repeating character in the arra...read more
Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits