1
var maxDistance = function (colors) {
2
// using two pointers from start and end
3
// Time complexity O(n)
4
// Space complexity O(1)
5

6
const start = 0;
7
const end = colors.length - 1;
8

9
// maximum distance possible is length of arr, so start with two pointer
10
// one at the start and one at the end
11
const startColor = colors[start];
12
const endColor = colors[end];
13

14
// base condition, to check if they are not already equal
15
if (startColor !== endColor) {
16
return end;
17
}
18

19
// move the forward pointer till we find the differend color
20
let forwardPtr = start;
21
while (startColor === colors[forwardPtr]) {
22
++forwardPtr;
23
}
24

25
// move the backward pointer till we find the differend color
26
let backwardPtr = end;
27
while (endColor === colors[backwardPtr]) {
28
--backwardPtr;
29
}
30

31
// Till here, We already know that startColor === endColor
32
// hence we did two things,
33
// 1. we kept startColor fixed and moved backwardPtr till we find different color
34
// 2. similarly, we kept endColor fixed and moved the forwardPtr till we find the different color.
35
// we will return the max different out of two now.
36
return Math.max(Math.abs(start - backwardPtr), Math.abs(end - forwardPtr));
37
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0