Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Sort Balls by Color

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Sort Balls by Color. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Sort an array of balls that come in 2 colors so that same colors are grouped together.

Asked in the Round 1 (90 min) stage. This is a LeetCode-style Sort Colors variant. Reported follow-up: generalize to sort n balls of k colors.

Input and Output

Implement sort_two_colors(balls), where balls is a list containing only 0 and 1. Rearrange the list in place so all 0s appear before all 1s, and return the same list.

Constraints

  • 0 <= len(balls) <= 10^5
  • Each element of balls is either 0 or 1
  • The rearrangement must be performed in place

Function Signature

def sort_two_colors(balls):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output