Slow read pointer + fast write pointer (or different speeds), both moving forward
When to useIn-place array filtering/dedup, reading at one rate while writing at another, cycle detection
iterative
Remove Element
remove_elementRemove Vowels
remove_vowelsString Compression
string_compressionMove Zeros
move_zerosRemove Duplicates
remove_duplicatesLongest Substring Without Two Contiguous Occurrences of Letter
longest_substring_without_3_contiguous_occurrences_letterString Without 3 Identical Consecutive Letters
string_without_3_identical_consecutive_lettersSort Colorsmedium
sort_colors · no slotsINITIALIZE
slow=0; fast=0 (or different rates)
let slow = 0; let fast = 0;
const vowels = 'aeiouAEIOU'; const out = [];
let result = ''; let slow = 0;
let slow = 0; let fast = 0;
let slow = 0; let fast = 0;
let slow = 0; let fast = 0;
const res = s.split(''); let slow = 2;
—
TRAVERSE
for (fast = 0; fast < n; fast++)
for (let fast = 0; fast < nums.length; fast++) {
for (const char of s) {
for (let fast = 1; fast <= s.length; fast++) {
for (let fast = 0; fast < arr.length; fast++) {
for (let fast = 0; fast < arr.length; fast++) {
for (; fast < s.length; fast++) {
for (let fast = 2; fast < s.length; fast++) {
—
[DECIDE]
decide whether to keep current fast value
if (nums[fast] !== target) {
if (!vowels.includes(char)) {
if (fast === s.length || s[fast] !== s[slow]) {
if (arr[fast] !== 0) {
if (arr[fast] !== arr[slow]) {
// decide whether to keep s[fast] (run-length grouping, not canonical slow/fast)
if (s[fast] !== res[slow - 1] || s[fast] !== res[slow - 2]) {
—
write+advance
if keep, write to slow position; advance slow
nums[slow] = nums[fast]; slow++;
out.push(char);
result += s[slow] + (fast - slow); slow = fast;
arr[slow] = arr[fast]; slow++;
slow++; arr[slow] = arr[fast];
// append kept chars; advance slow
res[slow] = s[fast]; slow++;
—
RETURN
return slow (often new length or transformed value)
return nums.slice(0, slow);
return out.join('');
return result;
// fill tail with zeros, then return arr
return slow + 1;
return ans;
return res.slice(0, slow).join('');
—