Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Check if a given Bit is Set or Not using JavaScript
Next article icon

JavaScript Program to Check if all Bits can be made Same by Single Flip

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach.

Examples:

Input: 1101
Output: Yes
Explanation: In 1101, the 0 can be flipped to make it all 1

Input: 11
Output: No
Explanation: No matter whichever digit you
flip, you will not get the desired string.
Input: 1
Output: Yes
Explanation: We can flip 1, to make all 0's

Table of Content

  • Approach 1: Counting 0's and 1's
  • Approach 2: XOR Operation in JavaScript
  • Approach 3: Using split and filter
  • Approach 4: Using Regular Expression

Approach 1: Counting 0's and 1's

To check if all bits can be made the same by a single flip in JavaScript, you can follow these steps:

  • Count the number of 0s and 1s in the given binary sequence.
  • If the count of 0s is 1 or the count of 1s is 1, then it's possible to make all bits the same by a single flip. Otherwise, it's not possible.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
code here...
}

Example: Below is the implementation of the above approach

JavaScript
function canMakeAllBitsSameBySingleFlip(binaryString) {     let countZeros = 0;     let countOnes = 0;      for (let i = 0;         i < binaryString.length;         i++) {         if (binaryString[i] === '0') {             countZeros++;         } else if (binaryString[i] === '1') {             countOnes++;         } else {                      // If the input contains non-binary              // characters, return false             return false;         }     }      // Check if it's possible to make      // all bits the same by a single flip     return countZeros === 1 || countOnes === 1; }  // True, because you can flip one  // '0' to '1' to make all bits the same. const binaryString1 = "1101";  // False, because you can flip one '1' to '0' . const binaryString2 = "11";  // False, because it contains a non-binary character. const binaryString3 = "1010a";  console.log(canMakeAllBitsSameBySingleFlip(binaryString1)); console.log(canMakeAllBitsSameBySingleFlip(binaryString2)); console.log(canMakeAllBitsSameBySingleFlip(binaryString3));  

Output
true false false 

Time complexity: O(n) where n is the length of the string.

Approach 2: XOR Operation in JavaScript

Here we uses the XOR (exclusive OR) operation, is a bit manipulation technique to determine if it's possible to make all bits in a binary string the same by a single flip. Let's break down how this approach works:

  • Initialize XOR Result: Start with an initial XOR result of 0. This result will be used to track the parity (odd or even) of the number of '1's encountered in the binary string.
  • Iterate Through the Binary String: Traverse the binary string character by character from left to right.
  • XOR Operation: For each '1' encountered in the binary string, perform the XOR operation with the current XOR result. XORing a bit with 1 toggles its value: 0 XOR 1 = 1, and 1 XOR 1 = 0.

Syntax:

a^b

Example: Below is the implementation of the above approach

JavaScript
function Approach2(binaryString) {      // Check for invalid characters     if (/[^01]/.test(binaryString)) {         console.log(`"${binaryString}" -> false`);         return false;     }      let xorResult = 0;     let hasOne = false;     let hasZero = false;      for (let i = 0;         i < binaryString.length;         i++) {         if (binaryString[i] === '1') {             xorResult ^= 1;             hasOne = true;         } else             if (binaryString[i] === '0') {                 xorResult ^= 0;                 hasZero = true;             }     }  /*  If xorResult is 0 or 1 and         both '0' and '1' are present,      it's possible to make all bits      the same by a single flip  */     const result =         (xorResult <= 1) &&         (hasOne && hasZero);     console.log(`"${binaryString}" -> ${result}`);     return result; } // Example usage: const binaryString1 = "1101"; const binaryString2 = "11"; const binaryString3 = "111"; const binaryString4 = "1010a1";  Approach2(binaryString1); // true Approach2(binaryString2); // false Approach2(binaryString3); // false Approach2(binaryString4); // false 

Output
"1101" -> true "11" -> false "111" -> false "1010a1" -> false 

Time complexity: O(n) where n is the length of the string.

Approach 3: Using split and filter

The split and filter approach involves splitting the binary string into an array, then using filter to count the number of '0's and '1's. It checks if either count is exactly one, indicating that flipping a single bit will unify the string.

Example:

JavaScript
function canMakeSameBySingleFlip(str) {     let count0 = str.split('').filter(char => char === '0').length;     let count1 = str.split('').filter(char => char === '1').length;      return count0 === 1 || count1 === 1; }  console.log(canMakeSameBySingleFlip("1101")); // true console.log(canMakeSameBySingleFlip("1111")); // false 

Output
true false 

Approach 4: Using Regular Expression

In this approach, we utilize regular expressions to check if it's possible to make all bits in a binary string the same by performing a single flip operation. The regular expression approach can effectively count the occurrences of '0's and '1's in the string.

Example: This example demonstrates how to use regular expressions to determine if a binary string can be made uniform by flipping a single bit.

JavaScript
function canMakeUniformBySingleFlip(binaryString) {     // Count the number of '0's and '1's using regular expressions     const countZeros = (binaryString.match(/0/g) || []).length;     const countOnes = (binaryString.match(/1/g) || []).length;      // Check if either count of '0's or count of '1's is exactly one     if (countZeros === 1 || countOnes === 1) {         return "Yes";     } else {         return "No";     } }  // Test cases console.log(canMakeUniformBySingleFlip("1101")); // Output: Yes console.log(canMakeUniformBySingleFlip("11"));   // Output: No console.log(canMakeUniformBySingleFlip("1"));    // Output: Yes console.log(canMakeUniformBySingleFlip("101"));  // Output: No console.log(canMakeUniformBySingleFlip("1000")); // Output: Yes 

Output
Yes No Yes Yes Yes 



Next Article
Check if a given Bit is Set or Not using JavaScript
author
skaftafh
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

  • JavaScript Program for Min flips of continuous characters to make all characters same in a String
    In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensu
    3 min read
  • Check if a given Bit is Set or Not using JavaScript
    Bits in a number are fundamental components of binary representation and each bit in binary has only two states like 0 or 1. With the help of those two bits, we can represent any number in a binary format. And if a bit is to be set if it's value is 1 otherwise it is not set. Note: Indexing starts wi
    2 min read
  • JavaScript Program to FindNumber of Flips to make Binary String Alternate
    In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern. Examples: I
    4 min read
  • JavaScript Program to Check if a Number has Bits in an Alternate Pattern
    JavaScript can be used to assess whether a given number follows an alternating pattern in its binary representation. By examining the binary digits of the number, one can determine if the sequence alternates between 0s and 1s, aiding in understanding the binary structure of the input. Examples: Inpu
    2 min read
  • JavaScript Program to Compute the Bitwise OR of all Numbers in a Range
    In JavaScript, bitwise operations provide a way to manipulate individual bits of numeric values. The bitwise OR operation (|) combines the bits of two operands, resulting in a new value where each bit is set if it is set in either operand. Understanding Bitwise ORThe bitwise OR operation takes two o
    2 min read
  • Check if the ith Bit is Set or Not using JavaScript
    Checking if the ith bit is set or not in a binary representation is a common task in programming, especially in scenarios where bitwise operations are utilized. In this article, we'll explore multiple approaches to accomplish this using JavaScript. Given a non-negative integer num and an index i, we
    2 min read
  • Javascript Program to Check if two numbers are bit rotations of each other or not
    Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input :
    3 min read
  • Count Number of Bits to be Flipped to Convert A to B using JavaScript
    Given two numbers, A and B. Write a program to count the number of bits needed to be flipped to obtain B from A. Examples: Input: A = 10, B = 20Output: 4Explanation: Binary representation of A is 00001010Binary representation of B is 00010100We need to flip highlighted four bits in A to obtain B fro
    3 min read
  • Check if Binary Array can be made palindrome after K bitwise XOR with 1
    Given a binary array arr[] of size N and an integer K, the task is to check whether the binary array can be turned into a palindrome after K number of operations where in one operation, any random index can be chosen and the value stored in the index will be replaced by its bitwise XOR(^) with1. Exa
    9 min read
  • Check if it is possible to make all strings of A[] equal to B[] using given operations
    Consider two arrays, A[] and B[], each containing N strings. These strings are composed solely of digits ranging from 0 to 9. Then your task is to output YES or NO, by following that all the strings of A[] can be made equal to B[] for each i (1 <= i <= N) in at most K cost. The following opera
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences