Monday, November 18, 2024
Google search engine
HomeData Modelling & AINumber of groups of magnets formed from N magnets

Number of groups of magnets formed from N magnets

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.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments