Number of groups of magnets formed from N magnets in C++

The digit 1 represent positive pole whereas 0 represents negative pole.

The magnet will have both poles as 10 or 01. A group can be formed with the magnets that attracts each other. The magnets with different pole facing each other will be in the same group.

Here, you are given N number of magnets. You need to find out number of groups can be formed with them.

Whenever there are two different magnets side by side, there forms a new group. In that case increment the count of the groups.

Let's see an example.


magnets = ["10", "01", "01", "01", "10", "01"]



There are 4 magnets that attract each other side by side in the given array. They are "10", "01", "10", "01".


  • Initialise the array with magnets.
  • Initialise the count to 1 as we are taking pairs.
  • Write a loop that iterates from 1 index to the end of the array.
  • If the current magnet is not equal to the previous one, then increment the count.
  • Return the count.


Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getMangetGroupsCount(string magnets[], int n) {
   int count = 1;
   for (int i = 1; i < n; i++) {
      if (magnets[i] != magnets[i - 1]) {
   return count;
int main() {
   string magnets[] = { "10", "01", "01", "01", "10", "01" };
   int n = 6;
   cout << getMangetGroupsCount(magnets, n) << endl;
   return 0;


If you run the above code, then you will get the following result.


Updated on: 26-Oct-2021


Kickstart Your Career

Get certified by completing the course

Get Started