This question was asked in a recent Samsung R&D Online Assessment round.
There is a cylinder of height N, consisting of M rows, with M sections in each row.
Some sections have a star on them - denoted by the character 'S' - and the remaining sections are blank - denoted by the character '_'
In a single move, we can shift any 1 row by 1 element to the left, or by 1 element to the right.
Return the minimum number of moves in which the stars in each row can be vertically aligned.
Sample Input :-
N = 5, M = 12
(adding a single space between consecutive characters for readability, the sapce characters are not included in the actual input array provided)
_ S _ _ _ _ _ _ _ _ S _
_ _ _ _ _ _ _ _ _ _ _ S
S _ _ _ _ _ _ _ _ _ _ _
_ _ S _ _ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _ _ _ _ S
Output = 5
Explanation :-
Shift the 1st row by 1 to the right -> 1 move
Shift the 3rd row by 1 to the left -> 1 move
Shift the 4th row by 3 to the left -> 3 moves
1 + 1 + 3 = 5
After the above moves, the cylinder looks like this (the 'S' in the last column are vertically aligned one-below-the-other) :-
_ _ S _ _ _ _ _ _ _ _ S
_ _ _ _ _ _ _ _ _ _ _ S
_ _ _ _ _ _ _ _ _ _ _ S
_ _ _ _ _ _ _ _ _ _ _ S
_ _ _ _ _ _ _ _ _ _ _ S
Constraints :-
1 <= M <= 1000
1 <= N <= 1000
input.length == N
input[i].length == M for all i -> 0 <= i < M
input[i] consists of '_' and 'S' only.
There will always be at least 1 star in each row.
There may be more than 1 star in a row.class Solution {
public int solve(String input[], int N, int M) {
// Write code here
}
}