Endless Integer Sequence

4.4

7 votes
, Algorithms, Binary search tree, Binary Search, Trie
Problem

You have an infinite sequence of natural numbers as follows \([1, 2, 3, 4, 5, ...]\)

You need to perform these 2 types of queries on this infinite sequence,

  • Query 1
    • Delete an integer \(X\) from this infinite sequence.
    • After deleting the element, the remaining sequence is concatenated together.
      • for example, \([1, 2, 3, 4, 5...]\) and \(X = 3\) then after deletion, the resulting sequence will be \([1, 2, 4, 5, 6, ...]\)
  • Query 2
    • Find the \(Kth\) smallest integer in this infinite sequence.
    • For example, in the sequence \([1, 2, 3, 5, 6, 7, ...]\)
      • for \(K = 1\)\(Kth\) smallest will be \(1 \)
      • for \(K = 3\)\(Kth\) smallest will be \(3\)
      • for \(K = 5\)\(Kth\) smallest will be \(6\)

NOTE:

  • In Query 1, for the element to be deleted, it is provided that \(X\) will be present in the sequence at the time of query.

Input Format

  • First line contains an integer \(Q\), the number of queries.
  • Next \(Q\) lines contain 2 space-seperated integers denoting each query as follows,
    • \(1 \space \space X\)
      • Query 1, with parameter \(X\) the integer to be deleted.
    • \(2 \space \space K\)
      • Query 2, with parameter \(K\) to find \(Kth\) smallest element in the infinite sequence.

Output Format

  • For each Query of type 2, output a single integer denoting the \(Kth\) smallest element in the infinite integer sequence.

Constraints

  • \(1 \le Q \le 10^5\)
  • \(1 \le X \le 10^9\)
  • \(1 \le K \le 10^9\)
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation
  • Total 6 Queries.
  • Initially, sequence is \([1, 2, 3, 4, 5, ...]\)
  • First Query, print \(101st\) smallest element, ie. \(101\) as there are no deletions.
  • Second Query, Delete \(1\) from the sequence, new sequence \([2, 3, 4, 5, 6, ...]\)
  • Third Query, Print \(1st\) smallest element ie. \(2\)
  • Fouth Query, Delete \(2\) from the sequence, new sequence \([3, 4, 5, 6, 7, ...]\)
  • Fifth Query, Print \(1st\) smallest element, ie. \(3\)
  • Sixth Query, Print \(101st\) smallest element ie. \(103\)
Editor Image

?