Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add two pointer algorithm #12

Open
pathikrit opened this issue May 26, 2016 · 1 comment
Open

Add two pointer algorithm #12

pathikrit opened this issue May 26, 2016 · 1 comment

Comments

@pathikrit
Copy link
Owner

pathikrit commented May 26, 2016

  /**
    * Two pointer algorithm
    * O(2*n)
    * See:
    *   http://codeforces.com/contest/676/problem/C
    *   http://codeforces.com/contest/580/problem/B
    *
    * @param n maximum right bound
    * @param f given an interval returns if it is acceptable
    *        f must be monotonic i.e. for all super-interval j of i, f(j) implies f(i)
    *
    * @return List of all intervals in [0, n) at which f is acceptable
    */
  def validIntervals(n: Int)(f: (Int, Int) => Boolean): Iterator[(Int, Int)] = {
    val it = new Iterator[Option[(Int, Int)]] {
      var l, r = 0
      override def hasNext = r < n
      override def next() = {
        if(f(l, r)) {
          r += 1
          Some((l, r - 1))
        } else {
          if(l < r) l += 1 else r += 1
          None
        }
      }
    }
    it.flatten
  }
@pathikrit pathikrit changed the title Add Two pointer Add two pointer ALGORITHM May 28, 2016
@pathikrit pathikrit changed the title Add two pointer ALGORITHM Add two pointer algorithm May 28, 2016
@pathikrit
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant