Open In App

Number of groups of magnets formed from N magnets

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given N magnets are kept in a row one after another, either with a negative pole on the left and a positive pole on the right (01) or a positive pole on the left and a negative pole on the right (10). Considering the fact that if 2 consecutive magnets have different poles facing each other, they form a group and attract each other, find the total number of groups possible.

Examples:  

Input : N = 6, magnets = {10, 10, 10, 01, 10, 10}
Output : 3
Explanation: The groups are formed by the following magnets: {1, 2, 3},  {4}, {5, 6}

Input : N = 5, magnets = {10, 10, 10, 10, 10, 01}
Output : 2

Let us consider every pair of consecutive magnets. There are 2 possible cases:  

  • Both of them have the same configuration. In this case, the connecting ends will have different poles and hence they would belong to the same group.
  • Both of them have different configurations. In this case, the connecting ends will have the same pole and hence they would repel each other to form different groups.

So a new group will only be formed in the case when two consecutive magnets have different configurations. To traverse the array of magnets and find the number of consecutive pairs with the different configurations.

Below is the implementation of the above approach:  

C++




// C++ program to find number of groups
// of magnets formed from N magnets
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of groups of
// magnets formed from N magnets
int countGroups(int n, string m[])
{
    // Intinially only a single group
    // for the first magnet
    int count = 1;
 
    for (int i = 1; i < n; i++)
 
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
 
    return count;
}
 
// Driver Code
int main()
{
    int n = 6;
 
    string m[n] = { "10", "10", "10", "01", "10", "10" };
 
    cout << countGroups(n, m);
 
    return 0;
}


Java




// Java program to find the maximum number
// of elements that can be added to a set
// such that it is the absolute difference // of magnets formed from N magnets
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG{ 
     
// Function to count number of groups of
// magnets formed from N magnets
static int countGroups(int n, String m[])
{
    // Intinially only a single group
    // for the first magnet
    int count = 1;
   
    for (int i = 1; i < n; i++)
   
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
   
    return count;
}
   
// Driver Code
public static void main(String args[])
{
    int n = 6;
   
    String []m = { "10", "10", "10", "01", "10", "10" };
   
    System.out.println( countGroups(n, m));
   
}
}


Python 3




# Python 3 program to find number
# of groups of magnets formed
# from N magnets
 
# Function to count number of
# groups of magnets formed
# from N magnets
def countGroups(n, m):
 
    # Intinially only a single
    # group for the first magnet
    count = 1
 
    for i in range(1, n):
 
        # Different configuration increases
        # number of groups by 1
        if (m[i] != m[i - 1]):
            count += 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
 
    n = 6
 
    m = [ "10", "10", "10",
          "01", "10", "10" ]
 
    print(countGroups(n, m))
 
# This code is contributed
# by ChitraNayal


C#




// C# program to find number of groups
// of magnets formed from N magnets
using System;
 
class GFG {
 
    // Function to count number of groups of
    // magnets formed from N magnets
    static int countGroups(int n, String []m)
    {
         
        // Intinially only a single group
        // for the first magnet
        int count = 1;
     
        for (int i = 1; i < n; i++)
     
            // Different configuration increases
            // number of groups by 1
            if (m[i] != m[i - 1])
                count++;
     
        return count;
}
 
// Driver Code
public static void Main()
{
    int n = 6;
    String [] m = {"10", "10", "10",
                    "01", "10", "10"};
 
    Console.WriteLine(countGroups(n, m));
}
}
 
// This code is contributed by ANKITRAI1


Javascript




<script>
// Javascript program to find the maximum number
// of elements that can be added to a set
// such that it is the absolute difference
// of magnets formed from N magnets
     
// Function to count number of groups of
// magnets formed from N magnets
function countGroups(n,m) {
    // Intinially only a single group
    // for the first magnet
    let count = 1;
     
    for (let i = 1; i < n; i++)
     
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
     
    return count;
}
     
    // Driver Code
    let n = 6;
    let m=[ "10", "10", "10", "01", "10", "10"];
    document.write( countGroups(n, m));
     
 
// This code is contributed by rag2127
</script>


PHP




<?php
// PHP program to find number of groups
// of magnets formed from N magnets
 
// Function to count number of groups
// of magnets formed from N magnets
function countGroups($n, $m)
{
    // Intinially only a single group
    // for the first magnet
    $count = 1;
 
    for ($i = 1; $i < $n; $i++)
 
        // Different configuration increases
        // number of groups by 1
        if ($m[$i] != $m[$i - 1])
            $count++;
 
    return $count;
}
 
// Driver Code
$n = 6;
 
$m = array( "10", "10", "10",
            "01", "10", "10" );
 
echo(countGroups($n, $m));
 
// This code is contributed
// by Shivi_Aggarwal
?>


Output

3






Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(1)

Approach:

  • Initialize a stack and a variable called groups to 1.
  • Iterate through the magnets from left to right.
  • If the stack is empty or the top magnet has the same polarity as the current magnet, push it onto the stack.
  • Otherwise, pop all the magnets from the stack until a magnet with the same polarity as the current magnet is found.
  • Push the current magnet onto the stack.
  • Increment the number of groups.
  • After iterating through all the magnets, return the number of groups.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of groups of
// magnets formed from N magnets
int countGroups(int n, int magnets[])
{
    stack<int> s;
    int groups = 1; // Initially, only a single group for the first magnet
     
    for (int i = 0; i < n; i++) {
        if (s.empty() || s.top() == magnets[i]) {
            // If the stack is empty or the top magnet has the same polarity as the current magnet, push it onto the stack
            s.push(magnets[i]);
        } else {
            // Otherwise, pop all the magnets from the stack until a magnet with the same polarity as the current magnet is found
            while (!s.empty() && s.top() != magnets[i]) {
                s.pop();
            }
            s.push(magnets[i]); // Push the current magnet onto the stack
            groups++; // Increment the number of groups
        }
    }
     
    return groups;
}
 
// Driver Code
int main()
{
    int n = 6;
    int magnets[n] = {10, 10, 10, 01, 10, 10};
     
    cout << countGroups(n, magnets);
     
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        int n = 6;
        int[] magnets = {10, 10, 10, 01, 10, 10};
 
        System.out.println(countGroups(n, magnets));
    }
 
    public static int countGroups(int n, int[] magnets) {
        Stack<Integer> stack = new Stack<>();
        int groups = 1; // Initially, only a single group for the first magnet
 
        for (int i = 0; i < n; i++) {
            if (stack.isEmpty() || stack.peek() == magnets[i]) {
                // If the stack is empty or the top magnet has the same polarity as the current magnet, push it onto the stack
                stack.push(magnets[i]);
            } else {
                // Otherwise, pop all the magnets from the stack until a magnet with the same polarity as the current magnet is found
                while (!stack.isEmpty() && stack.peek() != magnets[i]) {
                    stack.pop();
                }
                stack.push(magnets[i]); // Push the current magnet onto the stack
                groups++; // Increment the number of groups
            }
        }
 
        return groups;
    }
}


Python3




def count_groups(n, magnets):
    s = []
    groups = 1  # Initially, only a single group for the first magnet
     
    for i in range(n):
        if not s or s[-1] == magnets[i]:
            # If the stack is empty or the top magnet has the same polarity as the current magnet, push it onto the stack
            s.append(magnets[i])
        else:
            # Otherwise, pop all the magnets from the stack until a magnet with the same polarity as the current magnet is found
            while s and s[-1] != magnets[i]:
                s.pop()
            s.append(magnets[i])  # Push the current magnet onto the stack
            groups += 1  # Increment the number of groups
     
    return groups
 
# Driver Code
if __name__ == "__main__":
    n = 6
    magnets = [10, 10, 10, 1, 10, 10]
     
    print(count_groups(n, magnets))
 
 # This code is contributed by shivamgupta0987654321


C#




using System;
using System.Collections.Generic;
 
class GFG {
    // Function to count number of groups of magnets formed
    // from N magnets
    static int CountGroups(int n, int[] magnets)
    {
        Stack<int> s = new Stack<int>();
        int groups = 1; // Initially, only a single group
                        // for the first magnet
 
        for (int i = 0; i < n; i++) {
            if (s.Count == 0 || s.Peek() == magnets[i]) {
                // If the stack is empty or the top magnet
                // has the same polarity as the current
                // magnet, push it onto the stack
                s.Push(magnets[i]);
            }
            else {
                // Otherwise, pop all the magnets from the
                // stack until a magnet with the same
                // polarity as the current magnet is found
                while (s.Count > 0
                       && s.Peek() != magnets[i]) {
                    s.Pop();
                }
                s.Push(magnets[i]); // Push the current
                                    // magnet onto the stack
                groups++; // Increment the number of groups
            }
        }
 
        return groups;
    }
 
    static void Main(string[] args)
    {
        int n = 6;
        int[] magnets = { 10, 10, 10, 01, 10, 10 };
 
        Console.WriteLine(CountGroups(n, magnets));
    }
}
 
// This code is contributed by shivamgupta0987654321


Javascript




function countGroups(n, magnets) {
    let stack = [];
    let groups = 1;
    for (let i = 0; i < n; i++) {
        if (stack.length === 0 || stack[stack.length - 1] === magnets[i]) {
            // If the stack is empty or the top magnet has the
            // same polarity as the current magnet push it onto the stack
            stack.push(magnets[i]);
        } else {
            // Otherwise, pop all the magnets from the stack until
            // magnet with the same polarity as the current magnet is found
            while (stack.length > 0 && stack[stack.length - 1] !== magnets[i]) {
                stack.pop();
            }
            stack.push(magnets[i]);
            groups++;
        }
    }
    return groups;
}
 
const n = 6;
const magnets = [10, 10, 10, 1, 10, 10];
 
console.log(countGroups(n, magnets));


Output

3






Time Complexity: O(n), where n is the number of magnets in the row, as we are iterating through each magnet only once.
Space Complexity: O(n), as in the worst case scenario (when all magnets have different polarities), we might need to store all n magnets in the stack.



Similar Reads

Number of ways of distributing N identical objects in R distinct groups with no groups empty
Given two integer N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups such that no groups are left empty. Examples: Input: N = 4, R = 2 Output: 3 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second
5 min read
Find maximum and minimum distance between magnets
Given coordinates of two pivot points (x0, y0) &amp; (x1, y1) in coordinates plane. Along with each pivot, two different magnets are tied with the help of a string of length r1 and r2 respectively. Find the distance between both magnets when they repel each other and when they are attracting each other. Examples : Input : x1=0, y1=0, x2=5, y2=0, r1
6 min read
Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups
Given N rows and M columns of a matrix, the task is to fill the matrix cells using first K integers such that: Each group of cells is denoted by a single integer.The difference between the group containing the maximum and the minimum number of cells should be minimum.All the cells of the same group should be contiguous i.e., for any group, two adja
11 min read
Maximize number of groups formed with size not smaller than its largest element
Given an array arr[] of N positive integers(1 ? arr[i] ? N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. Examples: Input: arr = {2, 3, 1, 2, 2}
7 min read
Count the minimum number of groups formed in a string
Given a string 'S' which comprises two or more uppercase English letters. The task is to count the minimum number of groups required to completely cover the string by replacing consecutive characters with the same single character. Examples: Input : S = "TTWWW"Output : 2Explanation : There are 2 groups formed. One by covering the 2 consecutive T an
7 min read
Maximum number of 3-person teams formed from two groups
Given two integers N1 and N2 where, N1 is the number of people in group 1 and N2 is the number of people in group 2. The task is to count the maximum number of 3-person teams that can be formed when at least a single person is chosen from both the groups.Examples: Input: N1 = 2, N2 = 8 Output: 2 Team 1: 2 members from group 2 and 1 member from grou
10 min read
Number of groups formed in a graph of friends
Given n friends and their friendship relations, find the total number of groups that exist. And the number of ways of new groups that can be formed consisting of people from every existing group. If no relation is given for any person then that person has no group and singularly forms a group. If a is a friend of b and b is a friend of c, then a b
11 min read
Count of distinct groups of strings formed after performing equivalent operation
Given an array arr[] of N strings consisting of lowercase alphabets, the task is to find the number of distinct groups of strings formed after performing the equivalent operation. Two strings are said to be equivalent if there exists the same character in both the strings and if there exists another string that is equivalent to one of the strings i
12 min read
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Given an array, arr[] of length N, and an integer K. The value of the i-th element is arr[i]. The task is to find the maximum number of groups such that for each group the product of the number of elements in that group and the minimum element is at least K. Note: Every element should belong to exactly one group and some elements may not be part of
8 min read
Minimum number of groups of nodes such that no ancestor is present in the same group
Given a tree of N nodes. The task is to form the minimum number of groups of nodes such that every node belong to exactly one group, and none of its ancestors are in the same group. The parent of each node is given (-1 if a node does not have a parent).Examples: Input: par[] = {-1, 1, 2, 1, 4} Output: 3 The three groups can be: Group 1: {1} Group 2
6 min read