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++
#include <bits/stdc++.h>
using namespace std;
int countGroups( int n, string m[])
{
int count = 1;
for ( int i = 1; i < n; i++)
if (m[i] != m[i - 1])
count++;
return count;
}
int main()
{
int n = 6;
string m[n] = { "10" , "10" , "10" , "01" , "10" , "10" };
cout << countGroups(n, m);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
static int countGroups( int n, String m[])
{
int count = 1 ;
for ( int i = 1 ; i < n; i++)
if (m[i] != m[i - 1 ])
count++;
return count;
}
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
def countGroups(n, m):
count = 1
for i in range ( 1 , n):
if (m[i] ! = m[i - 1 ]):
count + = 1
return count
if __name__ = = "__main__" :
n = 6
m = [ "10" , "10" , "10" ,
"01" , "10" , "10" ]
print (countGroups(n, m))
|
C#
using System;
class GFG {
static int countGroups( int n, String []m)
{
int count = 1;
for ( int i = 1; i < n; i++)
if (m[i] != m[i - 1])
count++;
return count;
}
public static void Main()
{
int n = 6;
String [] m = { "10" , "10" , "10" ,
"01" , "10" , "10" };
Console.WriteLine(countGroups(n, m));
}
}
|
Javascript
<script>
function countGroups(n,m) {
let count = 1;
for (let i = 1; i < n; i++)
if (m[i] != m[i - 1])
count++;
return count;
}
let n = 6;
let m=[ "10" , "10" , "10" , "01" , "10" , "10" ];
document.write( countGroups(n, m));
</script>
|
PHP
<?php
function countGroups( $n , $m )
{
$count = 1;
for ( $i = 1; $i < $n ; $i ++)
if ( $m [ $i ] != $m [ $i - 1])
$count ++;
return $count ;
}
$n = 6;
$m = array ( "10" , "10" , "10" ,
"01" , "10" , "10" );
echo (countGroups( $n , $m ));
?>
|
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;
int countGroups( int n, int magnets[])
{
stack< int > s;
int groups = 1;
for ( int i = 0; i < n; i++) {
if (s.empty() || s.top() == magnets[i]) {
s.push(magnets[i]);
} else {
while (!s.empty() && s.top() != magnets[i]) {
s.pop();
}
s.push(magnets[i]);
groups++;
}
}
return groups;
}
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 ;
for ( int i = 0 ; i < n; i++) {
if (stack.isEmpty() || stack.peek() == magnets[i]) {
stack.push(magnets[i]);
} else {
while (!stack.isEmpty() && stack.peek() != magnets[i]) {
stack.pop();
}
stack.push(magnets[i]);
groups++;
}
}
return groups;
}
}
|
Python3
def count_groups(n, magnets):
s = []
groups = 1
for i in range (n):
if not s or s[ - 1 ] = = magnets[i]:
s.append(magnets[i])
else :
while s and s[ - 1 ] ! = magnets[i]:
s.pop()
s.append(magnets[i])
groups + = 1
return groups
if __name__ = = "__main__" :
n = 6
magnets = [ 10 , 10 , 10 , 1 , 10 , 10 ]
print (count_groups(n, magnets))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int CountGroups( int n, int [] magnets)
{
Stack< int > s = new Stack< int >();
int groups = 1;
for ( int i = 0; i < n; i++) {
if (s.Count == 0 || s.Peek() == magnets[i]) {
s.Push(magnets[i]);
}
else {
while (s.Count > 0
&& s.Peek() != magnets[i]) {
s.Pop();
}
s.Push(magnets[i]);
groups++;
}
}
return groups;
}
static void Main( string [] args)
{
int n = 6;
int [] magnets = { 10, 10, 10, 01, 10, 10 };
Console.WriteLine(CountGroups(n, magnets));
}
}
|
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]) {
stack.push(magnets[i]);
} else {
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));
|
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.
Last Updated :
19 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...