Two Pointers - Summary


https://www.interviewbit.com/tutorial/two-pointers/
This topic in itself is not particularly broad. However, a lot of interviews tend to be a little biased to questions using this technique which prompted us to separate it out as another topic.
So, two pointer ( or N pointer for that matter ) is usually a really clever optimization on some bruteforce approches in certain condition.
Let us start looking at this with the help of a question. Then we will generalize our approach.
 
Example: 
Given a sorted array A ( sorted in ascending order ), 
find if there exists 2 integers A[i] and A[j] such that A[i] + A[j] = 0, i != j
 

Now, with the same analysis, as ‘i’ increases, A[i] also increases. 
And the number of iterations after which ‘j’ breaks also increases. 
But note what changes when ‘i’ moves to i + 1:
  • If A[i] + A[J] > 0,
  • Then A[i + 1] + A[J] is also greater than 0, as A[i + 1] > A[i]. 
    This means if we have tried J for ‘i’, then when moving to i + 1, we should only try values of j < J. 
    This concludes that our ‘j’ should be monotonically decreasing and we could re-write the above solution as :
        int j = A.size() - 1;    
        for (int i = 0; i < A.size(); i++) 
            for (; j > i; j--) {
                if (i != j && A[i] + A[j] == 0) return true; // solution found. 
                if (A[i] + A[j] < 0) break; // Clearly A[i] + A[j] would decrease as j decreases.
            }

Let us analyze the time complexity of the above solution. 
Let us say A.size() = n.
  • ‘i’ moves in total of n steps.
  • ‘j’ also moves in total of n steps 
    ( j– is executed atmost n times. Note that we are never increasing the value of j. Neither are we resetting it ).
That means we take in total of n + n steps = O(n).
In general, all two pointer approach work similarly. You look at the naive solution involving multiple loops and then you start analyzing the pattern on each loop. 
Try to look for monotonicity in one of the loops as other loops move forward. If you find that, you have found your optimization.

https://www.interviewbit.com/courses/programming/topics/two-pointers/
https://tp-iiita.quora.com/The-Two-Pointer-Algorithm
Motivation Problem: Given two sorted arrays A and B, each having length N and M respectively. Form a new sorted merged array having values of both the arrays in sorted format.

https://leetcode.com/articles/two-pointer-technique/
These kind of problems usually involve two pointers:
One slow-runner and the other fast-runner.
A classic example is to remove duplicates from a sorted array, which is available for you to practice here.
There is another variation to that:
One pointer starts from the beginning while the other pointer starts from the end.
https://www.geeksforgeeks.org/two-pointers-technique/\
Two pointer is really an easy and effective technique which is typically used for searching pairs in a sorted arrays.
Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X.
bool isPairSum(A[], N, X)
{
    // represents first pointer
    int i = 0;
  
    // represents second pointer
    int j = N - 1;
  
    while (i < j) {
  
        // If we find a pair
        if (A[i] + A[j] == X)
            return true;
  
        // If sum of elements at current
        // pointers is less, we move towards
        // higher values by doing i++
        else if (A[i] + A[j] < X)
            i++;
  
        // If sum of elements at current
        // pointers is more, we move towards
        // lower values by doing i++
        else
            j--;
    }
    return false;
}

The 2 pointer technique is mostly applicable in sorted arrays where we try to perform a search in O(N).
Unit 4 Two Pointers | LeetLintcode
2根指针有3种题型:
+
  1. 一个数组, 从两边向中间移动(对撞型)
  2. 一个数组, 同时向前移动(前向型)
  3. 两个数组(并行型)
  4. 重点是记住: 模版是死的, 人是活的. 不要拘泥于模版. 参见min Substring contains target把题做少, 即所有新题都往会的方法上面靠.

对撞型

inspired by Qsort's partition. 有2个类型的题目:
  1. 2 sum
  2. partition
  • 模版
  • Two sum模版
int i = 0, j = leng-1;
while (i < j) {
    if (a[i] + a[j] > sum) {
        do something
        j--;
    }
    else if (a[i] + aj] < sum) {
        do something
        i++;
    }
    else {
        do something
        i++/j--/
}
  1. 总结模版
int i = 0, j = leng-1;
while (i < j) {
    if (A[i]和A[j]满足某个条件) {
        j--;  // 直接跳过k ∈ [i+1, j-1] 和j组成的pair, 这需要证明. 也是O(n^2)-> O(n)的关键. 
        do something
    }
    else if (A[i]和A[j]不满足某个条件) {
        i++; // 直接跳过i和k E [i+1, j-1]组成的pair.
        do something
    }
    else {
        do something
        i++或者j--.
    }
}

Trapping water area

  • container with most water

  • 方法1: brute force.
    • 通过2层循环, 找到每一个pair组合构成的面积. O(n^2).
  • 方法2: 灌水型的都想到对撞型指针.
    • 条件是什么呢? 这里有个数学分析: 先找到l/r里面的短板. 那么重点来了: 不用循环i跟[i~j]的板子组成的container. 因为面积由短板决定. 所以若[i~j]之间有比i更小的板, 那么面积只会是heights[k] (k-i). 所以比[i,j]组成的小. 或者, 如果[i~j]之间有比i大的板子, 那么面积也只会是heights[i] (k-i). 因为k < j. 所以更小. 于是证明了, 每次只要找到短板构成的面积, 然后和全局res来update.

前向型

2类题目:
  1. 窗口类: 注意和sliding window不同, sliding window是给定了窗口大小, 找一个符合条件的窗口; 而two pointer的窗口型是指大小不确定, 找一个符合条件的窗口. 所以前者使用heap, deque维护. 后者通过指针来维护.
  2. 快慢类
  • 模版:
    int i,j;
    while (i < leng) {
      while (j < leng) {
          if (满足条件) {
              更新结果/HashMap
              j++;
          }
          else {
              break;
          }
      }
      更新结果/HashMap
      i++;
    }
    

Minimum Window Substring contains target string in source

题目: Given a set T of characters and a string S, find the minimum window in S which will contain all the characters in T in complexity O(n). S = “ADOBECODEBANC” T = “ABC” Minimum window is “BANC”.
  • 类似题目: longest substring with at most k distinct characters
  • Key: 重点在于理解前向型双指针的算法思想. 而不是生搬硬套九章模版(应该适当修改). 学习如何用HashMap来作为数组存在判定.
  • 分析: 我一开始按照九章的前向型模版套着写的, 很简单, 但是也不太好. 因为每一次都要对256个数字判断. 所以Time complexity是O(256N). 老师讲了用source hash - target hash的方法. 但是我写的有错. 不知道怎么处理找到window的时候怎么去掉第一个char, 以及更新状态(即所有全局变量).
  • 然后搜到了Leetcode的答案, 以及Rui Bi精彩的Java实现. 其实就是前向型双指针的使用, 不过和template有点小小区别.
    • 意思如图: . 关键在于实现. 特别是找到window之后, 怎么advance pointer以及更新状态?
  • 代码如下
    /**
   * http://xmruibi.github.io/2015/10/08/minimum-window-substring/
   * http://articles.leetcode.com/2010/11/finding-minimum-window-in-s-which.html
   */
  public String minWindow(String source, String target) {
    // preload for target checking
    if (source == null || source.length() == 0 || target == null || target.length() == 0) return "";

    int tarLen = target.length();
    HashMap<Character, Integer> dict = new HashMap<>();  // target hash
    for (char c : target.toCharArray())  // 简洁
      dict.put(c, dict.containsKey(c) ? dict.get(c) + 1 : 1);  // 好写法!

    int hitCount = 0; // record current window hits how many characters in target
    int l = 0; // record the left bound of current window
    int minWindow = source.length() + 1; // initial the minimum window length
    int start = 0;  // hold the global left bound of min window
    for (int r = 0; r < source.length(); r++) {
      char cur = source.charAt(r);  // 因为只考虑一个char, 所以保存起来, 避免每次都用charAt求.

      if (!dict.containsKey(cur)) continue;  // 若不符合, 就找下一个点.即增加right.

      dict.put(cur, dict.get(cur) - 1);    // 更新Target hash. 注意这个也同时表示了Diff hash. 即当前window和target hash之差. 所以找到一个window并不是说Target hash全为0. 例如AAAABC里面找ABC. 则第一个window就会导致Thash的A为-3.
      if (dict.get(cur) >= 0) hitCount++;  // 关键之一: 通过Target hash, 判定是否已经找到了一个有效字符. 负数的次数也是有用的, 表明当前window有多于target的target[j]. 这在前移left的时候用到.

      // check the windows has amount of this char more than it in target string
      // loop until the amount back to normal, but always reduce the prev index char
      while (hitCount == tarLen) {  // 满足条件的情况.
        if (minWindow > r - l + 1) {
          start = l;
          minWindow = r - l + 1;
        }
        char prevChar = source.charAt(l);
        if (dict.containsKey(prevChar)) {  // hashmap比int[256]好处在于存在就是target里的char.
          dict.put(prevChar, dict.get(prevChar) + 1);  // 关键2: 如何更新状态? 恢复dict即说明下一次for要继续找到prevChar.
          if (dict.get(prevChar) > 0) hitCount--;  // 当Target hash里面有正数个prevChar, 那就要找这个char, 于是hitcount恢复为自减1.
        }
        l++;
      }
    }
    //
    if (minWindow > source.length()) return "";  // 注意如果没找到, 应该回复空.
    return source.substring(start, start + minWindow);
  }
Read full article from Unit 4 Two Pointers | LeetLintcode

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts