Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Determine the final state of each bulb after processing all the elements of number[]
Next article icon

Determine the final state of each bulb after processing all the elements of number[]

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of bulbs[] initially in either 1 (i.e 'on') or 0 (i.e 'off') state and a list of numbers[], where each number represents a position in the bulb[] array. For each element in number[] you have to flip the state of bulbs at positions that are multiples of the prime factors of the chosen number. The task is to determine the final state (either 'on' or 'off') of each bulb in the array after processing all the elements of number[].

Note: This problem uses 1-based indices.

Examples:

Input: bulbs = [1, 1, 0, 0, 1, 1, 0, 1, 1, 1], number[] = [3, 8, 15]
Output: 1001000011
Explanation: Initial state=[1100110111]
numbers[0] = 3, there is one prime factor: {3}. After the states are changed, affected bulbs in bold:[1110100101]
numbers[1] = 4, there is one prime factor: (2). The states of the bulbs and the affected bulbs are[1011110000]
numbers[2] = 15, the prime factors are {3, 5). The states of the bulbs and the affected bulbs are[1001100010],[1001000011]
The final states are 1001000011.
Input: bulbs = [0,1,1,0,1,1,0,1,1,1], number[] = [3, 8, 6]
Output: 0110110111

Approach: The problem can be solved using the following approach:

The approach involves factorizing given numbers into their prime components, counting the occurrences of each prime factor, and toggling values in a binary array at positions that are multiples of prime factors with odd counts.

Step-by-step approach:

  • Iterate through each number in the numbers vector and factorize it.
    • Store prime factor counts in the unordered map unmap.
  • Iterate over all prime factor that are stored in unmap having odd frequency (only odd frequency elements would be usefull in flipping the states):
    • Toggle values in the given array bulbs at positions that are multiples of number[.

Below is the implementation of the approach:

C++
#include <bits/stdc++.h> using namespace std;  // Function to factorize the given number n and update the // prime factor counts in the unordered map unmap void solve(int n, unordered_map<int, int>& unmap) {     set<int> s; // Set to store prime factors     while (n % 2 == 0) {         s.insert(2);         n /= 2;     }     for (int i = 3; i <= sqrt(n); i += 2) {         while (n % i == 0) {             s.insert(i);             n /= i;         }     }     if (n > 2) {         s.insert(n);     }     for (int i : s) {         unmap[i]++;     } }  // Function to toggle values in the array at positions that // are multiples of n void change(vector<int>& bulbs, int n) {     for (int i = n - 1; i < bulbs.size(); i += n) {         bulbs[i] = !bulbs[i];     } }  int main() {     vector<int> bulbs{ 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 };     vector<int> numbers{ 3, 8, 15 };     unordered_map<int, int> unmap;      // Factorize each element in vector numbers and update     // the prime factor counts in the unordered map unmap     for (int i : numbers) {         solve(i, unmap);     }      // Modify the binary array based on the parity of prime     // factor counts     for (auto ele : unmap) {         if (ele.second & 1) {             change(bulbs, ele.first);         }     }      // Output the final modified array     for (int i : bulbs) {         cout << i << " ";     }      return 0; } 
Java
/*code by flutterfly */ import java.util.*;  public class Main {          // Function to factorize the given number n and update the     // prime factor counts in the HashMap unmap     static void solve(int n, HashMap<Integer, Integer> unmap) {         HashSet<Integer> s = new HashSet<>(); // Set to store prime factors         while (n % 2 == 0) {             s.add(2);             n /= 2;         }         for (int i = 3; i <= Math.sqrt(n); i += 2) {             while (n % i == 0) {                 s.add(i);                 n /= i;             }         }         if (n > 2) {             s.add(n);         }         for (int i : s) {             unmap.put(i, unmap.getOrDefault(i, 0) + 1);         }     }      // Function to toggle values in the array at positions that     // are multiples of n     static void change(ArrayList<Integer> bulbs, int n) {         for (int i = n - 1; i < bulbs.size(); i += n) {             bulbs.set(i, 1 - bulbs.get(i));         }     }      public static void main(String[] args) {         ArrayList<Integer> bulbs = new ArrayList<>(Arrays.asList(1, 1, 0, 0, 1, 1, 0, 1, 1, 1));         ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(3, 8, 15));         HashMap<Integer, Integer> unmap = new HashMap<>();          // Factorize each element in the vector numbers and update         // the prime factor counts in the HashMap unmap         for (int i : numbers) {             solve(i, unmap);         }          // Modify the binary array based on the parity of prime         // factor counts         for (Map.Entry<Integer, Integer> ele : unmap.entrySet()) {             if ((ele.getValue() & 1) == 1) {                 change(bulbs, ele.getKey());             }         }          // Output the final modified array         for (int i : bulbs) {             System.out.print(i + " ");         }     } } 
Python3
# code by Flutterfly from math import sqrt  # Function to factorize the given number n and update the # prime factor counts in the dictionary unmap def solve(n, unmap):     s = set()  # Set to store prime factors     while n % 2 == 0:         s.add(2)         n //= 2     for i in range(3, int(sqrt(n)) + 1, 2):         while n % i == 0:             s.add(i)             n //= i     if n > 2:         s.add(n)     for i in s:         unmap[i] = unmap.get(i, 0) + 1  # Function to toggle values in the array at positions that # are multiples of n def change(bulbs, n):     for i in range(n - 1, len(bulbs), n):         bulbs[i] = not bulbs[i]  if __name__ == "__main__":     bulbs = [1, 1, 0, 0, 1, 1, 0, 1, 1, 1]     numbers = [3, 8, 15]     unmap = {}      # Factorize each element in list numbers and update     # the prime factor counts in the dictionary unmap     for i in numbers:         solve(i, unmap)      # Modify the binary array based on the parity of prime     # factor counts     for ele in unmap.items():         if ele[1] & 1:             change(bulbs, ele[0])      # Output the final modified array     for i in bulbs:         print(int(i), end=" ")  # Convert boolean to integer for matching format 
C#
// code by flutterfly using System; using System.Collections.Generic;  class Program {     // Function to factorize the given number n and update the      // prime factor counts in the dictionary unmap     static void Solve(int n, Dictionary<int, int> unmap)     {         HashSet<int> s = new HashSet<int>(); // Set to store prime factors         while (n % 2 == 0)         {             s.Add(2);             n /= 2;         }         for (int i = 3; i <= Math.Sqrt(n); i += 2)         {             while (n % i == 0)             {                 s.Add(i);                 n /= i;             }         }         if (n > 2)         {             s.Add(n);         }         foreach (int i in s)         {             if (unmap.ContainsKey(i))                 unmap[i]++;             else                 unmap[i] = 1;         }     }      // Function to toggle values in the array at positions that      // are multiples of n     static void Change(List<int> bulbs, int n)     {         for (int i = n - 1; i < bulbs.Count; i += n)         {             bulbs[i] = bulbs[i] == 0 ? 1 : 0;         }     }      static void Main()     {         List<int> bulbs = new List<int> { 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 };         List<int> numbers = new List<int> { 3, 8, 15 };         Dictionary<int, int> unmap = new Dictionary<int, int>();          // Factorize each element in list numbers and update          // the prime factor counts in the dictionary unmap         foreach (int i in numbers)         {             Solve(i, unmap);         }          // Modify the binary array based on the parity of prime          // factor counts         foreach (var ele in unmap)         {             if ((ele.Value & 1) != 0)             {                 Change(bulbs, ele.Key);             }         }          // Output the final modified array         foreach (int i in bulbs)         {             Console.Write(i + " ");         }     } } 
JavaScript
// code by flutterfly // Function to factorize the given number n and update the  // prime factor counts in the map unmap function solve(n, unmap) {     let s = new Set(); // Set to store prime factors     while (n % 2 === 0) {         s.add(2);         n /= 2;     }     for (let i = 3; i <= Math.sqrt(n); i += 2) {         while (n % i === 0) {             s.add(i);             n /= i;         }     }     if (n > 2) {         s.add(n);     }     for (let i of s) {         unmap[i] = (unmap[i] || 0) + 1;     } }  // Function to toggle values in the array at positions that  // are multiples of n function change(bulbs, n) {     for (let i = n - 1; i < bulbs.length; i += n) {         bulbs[i] = !bulbs[i];     } }  let bulbs = [1, 1, 0, 0, 1, 1, 0, 1, 1, 1]; let numbers = [3, 8, 15]; let unmap = {};  // Factorize each element in array numbers and update  // the prime factor counts in the map unmap for (let i of numbers) {     solve(i, unmap); }  // Modify the binary array based on the parity of prime  // factor counts for (let ele in unmap) {     if (unmap[ele] % 2 === 1) {         change(bulbs, parseInt(ele));     } }  // Output the final modified array  console.log(bulbs.map(Number).join(' ')); 

Output
1 0 0 1 0 0 0 0 1 1 

Time Complexity: O(N * sqrt(M)).
Auxiliary Space: O(sqrt(M)) due to the unordered map storing prime factors in the solve function.


Next Article
Determine the final state of each bulb after processing all the elements of number[]

M

mishraaabcf9
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • prime-factor
  • Geeks Premier League 2023
Practice Tags :
  • Arrays

Similar Reads

    Check if each element of the given array is the product of exactly K prime numbers
    Given an array of numbers A = \{a\textsubscript{1}, a\textsubscript{2} ... a\textsubscript{n}\} and the value of k , check if each number a\textsubscript{i} \in A can be expressed as the product of exactly k prime numbers. For every element of the array print 'YES' if the condition is satisfied, els
    9 min read
    Find the size of the final imaginary Array after removing the balls
    Given 2 arrays color[]and radius[] of length N each representing N balls, where color[i] represents the color of the ith ball while radius[i] represents the radius of the ith ball. If two consecutive balls have the same color and size, both are removed from the array, the task is to find the length
    12 min read
    Find minimum elements after considering all possible transformations
    Given an array of three colors. The array elements have a special property. Whenever two elements of different colors become adjacent to each other, they merge into an element of the third color. How many minimum numbers of elements can be there in the array after considering all possible transforma
    8 min read
    Modify a given array by replacing each element with the sum or product of their digits based on a given condition
    Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements: If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all th
    8 min read
    Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 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