LeetCode Challenge: Counting 0s and 1s in a String

🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g4J85qey 💡 My thought process: If you have a block of three 0s followed by a block of two 1s (00011), you can only create two valid pairs: 01 and 0011. The smaller group always limits the number of matches you can make, which is why the code uses min(prev, curr). To keep track of this, the code uses prev for the size of the block you just finished and curr for the block you’re currently counting. As you go through the string, you keep increasing curr as long as the characters remain the same. The moment the character changes, like when you hit a 1 after a series of 0s, it means you've completed a block. You take the min of the old block and the new block, add it to your total, move the curr count into prev, and start over for the next group. There is one small issue in the code: because that addition only happens when the characters change, the very last block in the string doesn't get processed inside the loop. That’s why there is one extra result += min(prev, curr) at the very end to catch that final transition. 👉 My Solution: https://lnkd.in/gdK35f76 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories