Lädt...


🔧 2938. Separate Black and White Balls


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

2938. Separate Black and White Balls

Difficulty: Medium

Topics: Two Pointers, String, Greedy

There are n balls on a table, each ball has a color black or white.

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

In each step, you can choose two adjacent balls and swap them.

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

Example 1:

  • Input: s = "101"
  • Output: 1
  • Explanation: We can group all the black balls to the right in the following way:
    • Swap s[0] and s[1], s = "011".
    • Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.

Example 2:

  • Input: s = "100"
  • Output: 2
  • Explanation: We can group all the black balls to the right in the following way:
    • Swap s[0] and s[1], s = "010".
    • Swap s[1] and s[2], s = "001".
    • It can be proven that the minimum number of steps needed is 2.

Example 3:

  • Input: s = "0111"
  • Output: 0
  • Explanation: All the black balls are already grouped to the right.

Constraints:

  • 1 <= n == s.length <= 105
  • s[i] is either '0' or '1'.

Hint:

  1. Every 1 in the string s should be swapped with every 0 on its right side.
  2. Iterate right to left and count the number of 0 that have already occurred, whenever you iterate on 1 add that counter to the answer.

Solution:

To solve this problem efficiently, we can use a greedy approach with a two-pointer-like strategy. The key insight is that every 1 (black ball) should be moved past the 0s (white balls) that are to its right, minimizing the total number of swaps.

Approach

  1. Track the Number of 0s Encountered:

    • Iterate through the string from right to left.
    • Count the number of 0s encountered so far as you iterate.
    • When you encounter a 1, each 0 that is to its right contributes to a swap needed to move this 1 past those 0s.
    • Add the count of 0s to the total swaps each time you encounter a 1.
  2. Calculate the Total Swaps:

    • The total number of swaps required will be the sum of the number of 0s encountered when processing each 1.

Let's implement this solution in PHP: 2938. Separate Black and White Balls

<?php
/**
 * @param String $s
 * @return Integer
 */
function minSwapsToGroupBlackBalls($s) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example usage
$s1 = "101";
echo "Input: $s1\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s1) . "\n"; // Output: 1

$s2 = "100";
echo "Input: $s2\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s2) . "\n"; // Output: 2

$s3 = "0111";
echo "Input: $s3\n";
echo "Minimum swaps needed: " . minSwapsToGroupBlackBalls($s3) . "\n"; // Output: 0
?>

Explanation:

  1. Initialize Counters:

    • zeroCount is initialized to 0 and tracks the number of 0s encountered while iterating from right to left.
    • swaps keeps track of the minimum swaps needed to group the 1s (black balls) together.
  2. Iterate Through the String:

    • Loop through the string from right to left using a for-loop.
    • If the current character is 0, increment zeroCount as it represents a white ball that will need to be swapped with a 1 to its left.
    • If the current character is 1, add zeroCount to swaps because each 0 encountered after this 1 contributes to a swap.
  3. Return the Total Swaps:

    • The accumulated value of swaps represents the minimum number of swaps required to arrange all 1s to the right.

Time Complexity

  • Time Complexity: O(n) where n is the length of the string s. We iterate through the string once and perform constant-time operations for each character.
  • Space Complexity: O(1) as we only use a few variables (zeroCount and swaps).

Example Analysis

  • Example 1: Input: "101"

    • Iteration from right to left:
      • s[2] = '1': zeroCount = 0, swaps = 0
      • s[1] = '0': zeroCount = 1, swaps = 0
      • s[0] = '1': zeroCount = 1, add 1 to swaps, swaps = 1
    • Output: 1.
  • Example 2: Input: "100"

    • Iteration from right to left:
      • s[2] = '0': zeroCount = 1, swaps = 0
      • s[1] = '0': zeroCount = 2, swaps = 0
      • s[0] = '1': zeroCount = 2, add 2 to swaps, swaps = 2
    • Output: 2.
  • Example 3: Input: "0111"

    • Iteration from right to left:
      • s[3] = '1': zeroCount = 0, swaps = 0
      • s[2] = '1': zeroCount = 0, swaps = 0
      • s[1] = '1': zeroCount = 0, swaps = 0
      • s[0] = '0': zeroCount = 1, swaps = 0
    • Output: 0 (All 1s are already grouped).

This solution provides an efficient way to determine the minimum steps to separate black and white balls using PHP.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

...

🔧 2938. Separate Black and White Balls


📈 76.73 Punkte
🔧 Programmierung

🐧 For work/life separation, do you use separate accounts on the OS, separate OSes, or separate machines?


📈 46.08 Punkte
🐧 Linux Tipps

🔧 Count ways of selecting X red balls and Y blue balls


📈 45.75 Punkte
🔧 Programmierung

🎥 How Cricket balls and Tennis balls are made.


📈 45.75 Punkte
🎥 Video | Youtube

📰 Black Deals bei Marktkauf: CoffeeB-Maschine für 99 Euro mit Gratis-Balls und 25-Euro-Gutschein


📈 26.47 Punkte
📰 IT Nachrichten

🕵️ Vuln: IBM iNotes and Domino CVE-2016-2938 Cross Site Scripting Vulnerability


📈 25.02 Punkte
🕵️ Sicherheitslücken

🕵️ Vuln: IBM iNotes and Domino CVE-2016-2938 Cross Site Scripting Vulnerability


📈 25.02 Punkte
🕵️ Sicherheitslücken

🕵️ Medium CVE-2020-2938: Oracle Financial services loan loss forecasting and provisioning


📈 25.02 Punkte
🕵️ Sicherheitslücken

📰 USN-2938-1: Git vulnerabilities


📈 23.71 Punkte
🐧 Unix Server

📰 USN-2938-1: Git vulnerabilities


📈 23.71 Punkte
🐧 Unix Server

💾 Red Hat Security Advisory 2018-2938-01


📈 23.71 Punkte
💾 IT Security Tools

📰 Red Hat Security Advisory 2018-2938-01


📈 23.71 Punkte
🐧 Unix Server

🕵️ IBM iNotes up to 8.5.2 FP6 IF1 cross site scripting [CVE-2016-2938]


📈 23.71 Punkte
🕵️ Sicherheitslücken

📰 Red Hat Security Advisory 2019-2938-01


📈 23.71 Punkte
🐧 Unix Server

🕵️ CVE-2020-2938


📈 23.71 Punkte
🕵️ Sicherheitslücken

💾 Red Hat Security Advisory 2020-2938-01


📈 23.71 Punkte
💾 IT Security Tools

🕵️ CVE-2016-2315 | Git 2.8.0 Repository memory corruption (USN-2938-1 / XFDB-111524)


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2016-2324 | Git 2.8.0 Repository memory corruption (USN-2938-1 / XFDB-111523)


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2022-2938


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2022-2938 | Linux Kernel Pressure Stall use after free


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2019-2938 | Oracle MySQL Server up to 5.7.27/8.0.17 InnoDB input validation


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2024-2938 | Campcodes Online Examination System 1.0 updateCourse.php id sql injection


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2014-2938 | Hanon Faceid F710 up to 1.007.108 improper authentication (VU#767044)


📈 23.71 Punkte
🕵️ Sicherheitslücken

🕵️ CVE-2008-2938 | Apache Tomcat up to 6.0.16 path traversal (EDB-6229 / Nessus ID 34168)


📈 23.71 Punkte
🕵️ Sicherheitslücken

📰 Swiss Soccer Fans Protest Esports by Throwing Tennis Balls and Game Controllers On the Field


📈 23.53 Punkte
📰 IT Security Nachrichten

📰 Now Calling Balls and Strikes: Robot Umpires


📈 23.53 Punkte
📰 IT Security Nachrichten

📰 Smashing Security podcast #211: Fleeking, COVID-19 hacking, and Bitcoin balls-ups


📈 23.53 Punkte
📰 IT Security Nachrichten

📰 Golf balls, massage chairs, and pies: Cantaloupe lays out our cash-less future


📈 23.53 Punkte
📰 IT Nachrichten

📰 Smashing Security podcast #290: Uber, Rockstar, and crystal balls


📈 23.53 Punkte
📰 IT Security Nachrichten

📰 Technical Issues' Stall MLB's Adoption of Robots to Call Balls and Strikes


📈 23.53 Punkte
📰 IT Security Nachrichten

📰 A Lawsuit Over Costco Golf Balls Shows Why We Can't Have Nice Things For Cheap


📈 22.22 Punkte
📰 IT Security Nachrichten

matomo