There is a row of seats. Assume that it contains N seats adjacent to each other. There is a group of people who are already seated in that row randomly. i.e. some are sitting together & some are scattered.
An occupied seat is marked with a character 'x' and an unoccupied seat is marked with a dot ('.')
Now your target is to make the whole group sit together i.e. next to each other, without having any vacant seat between them in such a way that the total number of hops or jumps to move them should be minimum.
In one jump a person can move to the adjacent seat (if available).
The minimum total moves are achieved by grouping all people around the median of their current positions. This is because the sum of absolute differences from the median is minimized.
classSolution {
public:int seats(string &A) {
constint MOD =10000003;
vector<int> pos;
for (int i =0; i < A.size(); ++i) if (A[i] =='x') pos.push_back(i);
if (pos.empty()) return0;
int m = pos.size() /2, ans =0;
for (int i =0; i < pos.size(); ++i)
ans = (ans + abs(pos[i] - (pos[m] - m + i))) % MOD;
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintseats(String A) {
int MOD = 10000003;
List<Integer> pos =new ArrayList<>();
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) =='x') pos.add(i);
}
if (pos.size() == 0) return 0;
int m = pos.size() / 2, ans = 0;
for (int i = 0; i < pos.size(); i++) {
ans = (ans + Math.abs(pos.get(i) - (pos.get(m) - m + i))) % MOD;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
from typing import List
classSolution:
defseats(self, A: str) -> int:
MOD =10000003 pos = [i for i, c in enumerate(A) if c =='x']
ifnot pos:
return0 m = len(pos) //2 ans =0for i, p in enumerate(pos):
ans = (ans + abs(p - (pos[m] - m + i))) % MOD
return ans
This approach treats each contiguous group of people as a block and repeatedly merges the leftmost or rightmost group into its neighbor, always merging the smaller group first. This minimizes the total number of moves required to bring everyone together.