LogIn
I don't have account.
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
Adℹ

Sort an Array of 0s and 1s

HackFury
15 Views
Amazon Pay offer
Adℹ

Given an array consisting of only 0s and 1s, sort the array in ascending order (all 0s first, followed by all 1s). The sorting must be done in-place without using built-in sort.

Example 1


Input: arr = [0, 1, 1, 0, 1, 0, 0, 1]
Output: [0, 0, 0, 0, 1, 1, 1, 1]

Example 2


Input: arr = [1, 1, 1, 0, 0, 0]
Output: [0, 0, 0, 1, 1, 1]

Constraints

  • 1 <= arr.length <= 10^6

  • arr[i] ∈ {0,1}

Counting Method (Linear Time)

Idea We can simply count how many 0s (and 1s) exist in the array. Once we know that:

  • The first count0 positions should be filled with 0s

  • The rest should be filled with 1s

That's it, the array becomes sorted!

//---------------Java---------------------
public static void sortCounting(int[] arr) {
    int count0 = 0;
    for (int num : arr) {
        if (num == 0) count0++;
    }
    for (int i = 0; i < count0; i++) {
        arr[i] = 0;
    }
    for (int i = count0; i < arr.length; i++) {
        arr[i] = 1;
    }
}

Complexity Analysis

  • Time Complexity: O(n), Single pass to count + another to overwrite
  • Space Complexity: O(1), Sorting done in-place

Optimal Approach: Two-Pointer Swap (Single Pass)

we'll solve this problem in a single traversal, without counting, without extra passes and without using any extra space.

This technique is called the Two-Pointer Swap Approach, a pattern used widely in high-performance systems, competitive programming and algorithmic interviews.

Core Idea

We maintain two pointers:

  • left : starts from the beginning of the array

  • right : starts from the end of the array

The idea is simple:

  • If the element at left is already 0, it’s in the correct position -> move left forward.

  • If the element at left is 1, it should go to the end -> swap it with arr[right] and move right backward.

This process continues until left < right.

The array gradually gets partitioned into two regions, all 0s on the left and all 1s on the right similar to the partition step of QuickSort.

Step-by-Step Example

Let's dry-run this with a real example:

arr = [1, 0, 1, 0, 0, 1]
Step left right Action Array State
1 0 5 arr[left] = 1 -> swap with arr[right] [1, 0, 1, 0, 0, 1] -> [1, 0, 1, 0, 0, 1] (same since right also 1)
2 0 4 arr[left] = 1 -> swap with arr[right] [0, 0, 1, 0, 1, 1]
3 1 3 arr[left] = 0 -> left++ [0, 0, 1, 0, 1, 1]
4 2 3 arr[left] = 1 -> swap with arr[right] [0, 0, 0, 1, 1, 1]
Done left >= right Sorted array: [0, 0, 0, 1, 1, 1]
//-----------------Java-----------------
public static void sortTwoPointer(int[] arr) {
    int left = 0, right = arr.length - 1;
    while (left < right) {
        if (arr[left] == 0) {
            left++;
        } else {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            right--;
        }
    }
}

Complexity Analysis

  • Time Complexity: O(n), Each element is checked once
  • Space Complexity: O(1), Sorting is done in-place

Complexity Comparison of All Approaches

Approach Time Complexity Space Complexity Passes
Counting Approach O(n) O(1) 2
Two-Pointer (Optimal) O(n) O(1) 1
Responses (0)

Write a response

CommentHide Comments

No Comments yet.

"},"4":{"id":4,"name":"ZEBRONICS Blanc mouse ad","otherData":"{}","contentFormat":2,"content":"
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
"},"2":{"id":2,"name":"Crousal Ads","otherData":"{}","contentFormat":2,"content":"
Sponsored -34%
iQOO Amazon's Choice

iQOO Z10 Lite 5G — Cyber Green, 4GB RAM, 128GB Storage

Dimensity 6300 · 50MP Sony AI Camera · 6000 mAh · IP64

★★★★★ 4.0 (2,052) 500+ bought last month
₹18,997 M.R.P. ₹28,999Save ₹10,002
Buy Now
"},"1":{"id":1,"name":"Banner Ads","otherData":"{}","contentFormat":2,"content":"\n
\n \n \n \"Amazon\n \n
"}}},"blogDetails":{"isWriter":false,"likes":0,"isLikedByUser":false,"tagIds":[17,62,133,169],"tags":[{"id":17,"name":"Array","maskingName":"array","isFeatured":true},{"id":62,"name":"Sorting","maskingName":"sorting","isFeatured":true},{"id":133,"name":"Coding Problems","maskingName":"coding-problems","isFeatured":true},{"id":169,"name":"Two Pointes","maskingName":"two-pointers","isFeatured":true}],"comments":[],"bookmark":{"isBookmarked":false,"count":0},"author":{"userId":"MjlfNF84LVs0XTJuLXRDX0FOZ2VfX0l0","name":"HackFury"},"viewCount":14,"showBannerImage":false,"seoTags":null,"content":"

Given an array consisting of only 0s and 1s, sort the array in ascending order (all 0s first, followed by all 1s).\nThe sorting must be done in-place without using built-in sort.

\n

Example 1

\n
\nInput: arr = [0, 1, 1, 0, 1, 0, 0, 1]\nOutput: [0, 0, 0, 0, 1, 1, 1, 1]\n
\n

Example 2

\n
\nInput: arr = [1, 1, 1, 0, 0, 0]\nOutput: [0, 0, 0, 1, 1, 1]\n
\n

Constraints

\n\n

Counting Method (Linear Time)

\n

Idea\nWe can simply count how many 0s (and 1s) exist in the array.\nOnce we know that:

\n\n

That's it, the array becomes sorted!

\n
//---------------Java---------------------\npublic static void sortCounting(int[] arr) {\n    int count0 = 0;\n    for (int num : arr) {\n        if (num == 0) count0++;\n    }\n    for (int i = 0; i < count0; i++) {\n        arr[i] = 0;\n    }\n    for (int i = count0; i < arr.length; i++) {\n        arr[i] = 1;\n    }\n}\n
\n

Complexity Analysis

\n\n

Optimal Approach: Two-Pointer Swap (Single Pass)

\n

we'll solve this problem in a single traversal, without counting, without extra passes and without using any extra space.

\n

This technique is called the Two-Pointer Swap Approach, a pattern used widely in high-performance systems, competitive programming\nand algorithmic interviews.

\n

Core Idea

\n

We maintain two pointers:

\n\n

The idea is simple:

\n\n

This process continues until left < right.

\n

The array gradually gets partitioned into two regions, all 0s on the left and all 1s on the right similar to the partition step of QuickSort.

\n

Step-by-Step Example

\n

Let's dry-run this with a real example:

\n
arr = [1, 0, 1, 0, 0, 1]\n
\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
StepleftrightActionArray State
105arr[left] = 1 -> swap with arr[right][1, 0, 1, 0, 0, 1] -> [1, 0, 1, 0, 0, 1] (same since right also 1)
204arr[left] = 1 -> swap with arr[right][0, 0, 1, 0, 1, 1]
313arr[left] = 0 -> left++[0, 0, 1, 0, 1, 1]
423arr[left] = 1 -> swap with arr[right][0, 0, 0, 1, 1, 1]
Doneleft >= rightSorted array: [0, 0, 0, 1, 1, 1]
\n
//-----------------Java-----------------\npublic static void sortTwoPointer(int[] arr) {\n    int left = 0, right = arr.length - 1;\n    while (left < right) {\n        if (arr[left] == 0) {\n            left++;\n        } else {\n            int temp = arr[left];\n            arr[left] = arr[right];\n            arr[right] = temp;\n            right--;\n        }\n    }\n}\n
\n

Complexity Analysis

\n\n

Complexity Comparison of All Approaches

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ApproachTime ComplexitySpace ComplexityPasses
Counting ApproachO(n)O(1)2
Two-Pointer (Optimal)O(n)O(1)1
","categoryId":177,"subCategoryId":177,"contentFormat":5,"blogId":24,"userId":"MjlfNF84LVs0XTJuLXRDX0FOZ2VfX0l0","title":"Sort an Array of 0s and 1s","url":"sort-an-array-of-0s-and-1s","bannerImage":"","seoDescription":"","generatedOn":"2025-10-05T06:45:30","updatedOn":"2025-10-05T06:45:30"},"popularContents":[{"id":34,"title":"System Design Deep Dive: 25 Essential Interview Questions","url":"system-design-deep-dive-25-essential-interview-questions","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-15T14:07:05.519481Z","viewCount":0},{"id":130,"title":"Rippling SDE-2 Interview Experience (4+ Years Experience) | Offer Received | Coding, LLD & System Design","url":"rippling-sde-2-interview-experience-4-years-experience-offer-received-coding-lld-system-design","description":null,"seoDescription":"Detailed Rippling SDE-2 interview experience with complete 5 rounds, coding questions, rules engine design, system design and preparation tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194847Z","viewCount":0},{"id":163,"title":"Top 50 SQL Interview Questions and Answers (Beginner to Intermediate)","url":"top-sql-interview-questions-and-answers-beginner-to-intermediate","description":null,"seoDescription":"Top 50 SQL Interview Questions and Answers (Beginner to Intermediate). Top SQL Interview Questions for fresher. Frequently asked SQL interview questions with answers","contentType":2,"generatedOn":"2026-10-15T14:07:05.518748Z","viewCount":0},{"id":167,"title":"Meesho SDE-1 Online Assessment Interview Experience (Remote) - Rejected","url":"meesho-sde-1-online-assessment-interview-experience-remote-rejected","description":null,"seoDescription":"Read a real Meesho SDE-1 online assessment experience with coding questions, DSA topics, solutions, difficulty level, preparation tips and interview insights.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194886Z","viewCount":0},{"id":138,"title":"DSA Patterns for Coding Interviews: Complete LeetCode Roadmap (Beginner to Advanced)","url":"dsa-patterns-for-coding-interviews-complete-leetcode-roadmap-beginner-to-advanced","description":null,"seoDescription":"Master every LeetCode pattern for coding interviews. Learn Arrays, Sliding Window, Graphs, Dynamic Programming, Trees, Heaps and more with 250+ curated problem","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194875Z","viewCount":0},{"id":135,"title":"Spinny SDE-1 Interview Experience (Selected)","url":"spinny-sde-1-interview-experience-selected","description":null,"seoDescription":"Spinny SDE-1 Interview Experience (Selected) | 4 Rounds Breakdown: Coding, LLD, Java, SQL + Real Interview Questions","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194861Z","viewCount":0},{"id":165,"title":"Top 50+ SQL Interview Questions and Answers for Intermediate to Advanced","url":"top-sql-interview-questions-and-answers-for-intermediate-to-advanced","description":null,"seoDescription":"Top SQL Interview Questions and Answers for Intermediate to Advanced. Top SQL Interview Questions for experience. Frequently asked SQL interview questions with answers","contentType":2,"generatedOn":"2026-10-15T14:07:05.5187519Z","viewCount":0},{"id":172,"title":"Google L4 Software Engineer III interview experience | Selected","url":"google-l4-software-engineer-iii-interview-experience-selected","description":null,"seoDescription":"Google L4 Software Engineer III interview experience with API design, Googlyness, route matching, graph coding rounds, follow-up questions and tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194924Z","viewCount":0},{"id":168,"title":"Amazon SDE-2 Interview Experience (3 Years Experience)","url":"amazon-sde-2-interview-experience-3-years-experience","description":null,"seoDescription":" Read a real Amazon SDE-2 interview experience covering the online assessment, coding rounds, object-oriented design, leadership principles and system design.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194901Z","viewCount":0},{"id":171,"title":"Meesho SDE-1 Backend Interview Experience (Remote | 3 Round) - Rejected","url":"meesho-sde-1-backend-interview-experience-remote-3-round-rejected","description":null,"seoDescription":"Read a real Meesho SDE-1 Backend interview experience covering the online assessment, DSA interview, machine coding round, LLD questions and preparation tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5194913Z","viewCount":0}],"latestContents":[{"id":219,"title":"6 Tools That Made My Life Easier as a Software Engineer","url":"6-tools-that-made-my-life-easier-as-a-software-engineer","description":null,"seoDescription":"The 6 developer tools I use daily as a software engineer: Git, VS Code, Docker, Postman, Chrome DevTools, and AI assistants, with real tips, mistakes, and trade","contentType":5,"generatedOn":"2026-10-15T14:07:05.5180946Z","viewCount":0},{"id":218,"title":"When Should a Business Use Multiple AI Agents Instead of One?","url":"when-should-a-business-use-multiple-ai-agents-instead-of-one","description":null,"seoDescription":"Single agent or multi-agent AI? Learn the 4 signals that justify splitting agents by knowledge, permissions, and risk, plus routing and handoff tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.518098Z","viewCount":0},{"id":216,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-15T14:07:05.5180995Z","viewCount":0},{"id":217,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181009Z","viewCount":0},{"id":215,"title":"What Happens When an AI Agent Doesn't Know the Answer?","url":"what-happens-when-an-ai-agent-doesnt-know-the-answer","description":null,"seoDescription":"Most AI agents fail quietly. They guess instead of saying \"I don't know.\" Here's how to design better fallback and human-handoff behavior.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181021Z","viewCount":0},{"id":214,"title":"Greedy Algorithms Explained: How They Work, When They Fail and How to Use Them","url":"greedy-algorithms-explained-how-they-work-when-they-fail-and-how-to-use-them","description":null,"seoDescription":"Learn greedy algorithms step by step with C# code Dijkstra, Huffman coding, knapsack and MSTs plus when greedy fails and how to prove it's correct","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181038Z","viewCount":0},{"id":213,"title":"Amazon SDE II Interview Experience (Bangalore, Selected) ~ Aug 2026","url":"amazon-sde-ii-interview-experience-bangalore-selected-aug-2026","description":null,"seoDescription":"Amazon SDE II interview experience from Bangalore covering 4 rounds, DSA, LLD, system design, Leadership Principles, coding questions and selection.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181051Z","viewCount":0},{"id":212,"title":"How to Get 10x Better AI Answers Without Writing Better Prompts : 10 Proven Techniques","url":"how-to-get-10x-better-ai-answers-without-writing-better-prompts-10-proven-techniques","description":null,"seoDescription":"Get better AI answers without complex prompts. Learn 10 practical techniques using context, examples, tools, feedback, and verification.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181064Z","viewCount":0},{"id":211,"title":"I Interviewed for a Microsoft SDE I Role. Here's Everything That Happened.","url":"i-interviewed-for-a-microsoft-sde-i-role-heres-everything-that-happened","description":null,"seoDescription":"My real Microsoft SDE I interview experience, all 4 rounds, the exact DSA problems with fully tested solutions, the WhatsApp system design round","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181078Z","viewCount":0},{"id":140,"title":"PolicyBazaar Software Development Engineer (SDE) Interview Experience | DSA, Core CS & System Design","url":"policybazaar-software-development-engineer-sde-interview-experience-dsa-core-cs-system-design","description":null,"seoDescription":"Detailed PolicyBazaar SDE interview experience covering 3 rounds: DSA coding, core CS assessment and system design with key learnings and insights.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5181093Z","viewCount":0}],"relatedContents":[{"id":207,"title":"How to Find the Right View of a Binary Tree","url":"right-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the right view of a binary tree using DFS and BFS, with examples, code, complexity analysis and coding interview tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282486Z","viewCount":0},{"id":206,"title":"Left View of a Binary Tree: DFS and BFS Approaches Explained","url":"left-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the left view of a binary tree using DFS and BFS, with examples, code, complexity analysis, common mistakes and interview tips.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282527Z","viewCount":0},{"id":205,"title":"Top View of a Binary Tree Using BFS and DFS | Complete Guide","url":"top-view-of-a-binary-tree","description":null,"seoDescription":"Learn how to find the top view of a binary tree using DFS and BFS with step-by-step explanations, examples, code, complexity analysis and interview insights.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282541Z","viewCount":0},{"id":201,"title":"Bottom View of a Binary Tree: DFS vs BFS Approach","url":"bottom-view-of-a-binary-tree-dfs-vs-bfs-approach","description":null,"seoDescription":"Learn to find the bottom view of a binary tree using horizontal distance. Compares a buggy DFS attempt, a fixed DFS and the optimal BFS solution in Java.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282553Z","viewCount":0},{"id":200,"title":" Longest Playlist With No Repeated Songs : Brute Force to Optimal","url":"longest-playlist-with-no-repeated-songs-brute-force-to-optimal","description":null,"seoDescription":"Find the longest playlist with no repeated songs using brute force, HashSet, and HashMap sliding window techniques, with Java code and dry runs.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282564Z","viewCount":0},{"id":90,"title":"Contain Virus : Deep, Intuitive & Fully Explained Guide","url":"contain-virus-deep-intuitive-fully-explained-guide","description":null,"seoDescription":"Contain Virus problem explained with DFS + greedy approach, step-by-step simulation, examples and optimized solutions for coding interviews.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282579Z","viewCount":0},{"id":37,"title":"Find the repeating and missing numbers","url":"find-the-repeating-and-missing-numbers","description":null,"seoDescription":"Find the repeating and missing numbers in an array from 1..n using brute force, hashmap, math and XOR, step-by-step explained with real-world use cases.","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282591Z","viewCount":0},{"id":27,"title":"4 Sum | Find Quads that add up to a target value","url":"4-sum-find-quads-that-add-up-to-a-target-value","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282602Z","viewCount":0},{"id":26,"title":"Top 50 Most Frequently Asked String Coding Problems (Interview Preparation )","url":"top-50-most-frequently-asked-string-coding-problems-interview-preparation","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282615Z","viewCount":0},{"id":25,"title":"Intersection of Two Sorted Arrays","url":"intersection-of-two-sorted-arrays","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-15T14:07:05.5282627Z","viewCount":0}]}}},"source":{"isMobile":false}}; window.__CLIENT_RENDER__ = false;