Sorting Array with Dutch National Flag Algorithm

🚀 #100DaysOfCode – Day 17 | DSA Practice Continuing my 100 Days Data Structures and Algorithms challenge, today I solved a very important problem based on arrays and the Dutch National Flag Algorithm. 📌 Problem: Sort Colors Given an array nums containing only 0, 1, and 2, sort the array in-place so that all 0’s, 1’s, and 2’s are grouped together in order. Example: Input: nums = [2,0,2,1,1,0] Output → [0,0,1,1,2,2] 🧠 Approach / Logic: 1️⃣ Use three pointers: • low → for placing 0’s • mid → to traverse the array • high → for placing 2’s 2️⃣ Traverse the array while mid <= high. 3️⃣ If the current element is: • 0 → swap with low, move both low and mid forward • 1 → just move mid forward • 2 → swap with high, move high backward 4️⃣ Continue this process until the entire array is sorted. 📊 Time Complexity: O(n) 📦 Space Complexity: O(1) 🎯 Key Learning: This problem demonstrates the power of the Dutch National Flag Algorithm, which helps sort elements efficiently in a single pass without extra space. Consistency is the key to growth. Let’s keep improving every day! 💪 #100DaysOfCode #DSA #CodingJourney #ProblemSolving #CPP #LearningInPublic

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories