1+ class  TwoPointers  { 
2+  /** 
3+  * Move Zeroes using Two Pointers 
4+  * @param  {number[] } nums - Input array 
5+  */ 
6+  moveZeroesTwoPointers ( nums )  { 
7+  let  left  =  0 ;  // Pointer for placing non-zero elements 
8+ 
9+  // Iterate with right pointer 
10+  for  ( let  right  =  0 ;  right  <  nums . length ;  right ++ )  { 
11+  if  ( nums [ right ]  !==  0 )  { 
12+  // Swap elements if right pointer finds a non-zero 
13+  [ nums [ left ] ,  nums [ right ] ]  =  [ nums [ right ] ,  nums [ left ] ] ; 
14+  left ++ ;  // Move left pointer forward 
15+  } 
16+  } 
17+  } 
18+ 
19+  /** 
20+  * Brute Force approach for Container with Most Water 
21+  * @param  {number[] } height - Array of heights 
22+  * @return  {number } - Maximum water that can be contained 
23+  */ 
24+  maxAreaBruteForce ( height )  { 
25+  let  maxArea  =  0 ; 
26+  let  n  =  height . length ; 
27+ 
28+  // Check all pairs (i, j) 
29+  for  ( let  i  =  0 ;  i  <  n ;  i ++ )  { 
30+  for  ( let  j  =  i  +  1 ;  j  <  n ;  j ++ )  { 
31+  // Compute the minimum height and width 
32+  let  minHeight  =  Math . min ( height [ i ] ,  height [ j ] ) ; 
33+  let  width  =  j  -  i ; 
34+  let  area  =  minHeight  *  width ;  // Compute water contained 
35+ 
36+  maxArea  =  Math . max ( maxArea ,  area ) ;  // Update max water 
37+  } 
38+  } 
39+  return  maxArea ; 
40+  } 
41+ 
42+  /** 
43+  * Two Pointers approach for Container with Most Water 
44+  * @param  {number[] } height - Array of heights 
45+  * @return  {number } - Maximum water that can be contained 
46+  */ 
47+  maxAreaTwoPointers ( height )  { 
48+  let  left  =  0 ,  right  =  height . length  -  1 ; 
49+  let  maxArea  =  0 ; 
50+ 
51+  // Move pointers toward each other 
52+  while  ( left  <  right )  { 
53+  let  width  =  right  -  left ;  // Distance between lines 
54+  let  minHeight  =  Math . min ( height [ left ] ,  height [ right ] ) ;  // Compute height 
55+  let  area  =  minHeight  *  width ;  // Compute water contained 
56+ 
57+  maxArea  =  Math . max ( maxArea ,  area ) ;  // Update max water 
58+ 
59+  // Move the pointer pointing to the shorter height 
60+  if  ( height [ left ]  <  height [ right ] )  { 
61+  left ++ ;  // Move left pointer forward 
62+  }  else  { 
63+  right -- ;  // Move right pointer backward 
64+  } 
65+  } 
66+  return  maxArea ; 
67+  } 
68+ } 
0 commit comments