## Google Interview Question

Software Engineers**Country:**United States

```
def makeheap( heap, start, N ):
for i in reversed( xrange( start, N/2 +1 ) ):
heapify( heap, i, N )
def heapify( heap, i, last ):
while(1):
l = i*2
r = i*2 +1
if l >= last:
return
if r >= last:
m = l
else:
if heap[l] <= heap[r]:
m = l
else:
m = r
if heap[m] < heap[i]:
heap[m],heap[i] = heap[i],heap[m]
i = m
else:
return
def lexi( arr, k):
n = len(arr )
heap = [ i for i in arr]
makeheap( heap, 0, len(arr))
h = dict()
for ind,i in enumerate(arr):
if i in h:
h[i].append( ind )
else:
h[i] = [ind]
i =0
start = 0
end = n - k
res = ""
last = n-1
c = 0
print h
while c < k:
print heap
index = h[ heap[0] ][0]
print index
if index > start and index < n - k+ c:
res+= heap[0]
c+=1
start = index
del h[heap[0]][0]
heap[0] = heap[last]
last-=1
heapify( heap, 0, last )
return res
print lexi( ["5","1","2","4","12","2"],2)
```

O(N), sliding window approach, returns start and end indices of subsequence.

```
#include <bits/stdc++.h>
using namespace std;
pair<int, int> lexographically_smallest(vector<int>& v, int k) {
assert (v.size() >= k );
int mul = pow(10, k - 1);
int cur = 0, ans = 0;
pair<int, int> result_pair = {0, k-1};
for (int i = k - 1; i >= 0; i --) ans += v[i] * pow(10, k - i - 1);
cur = ans;
// cout << "cur " << cur << endl;
for (int i = k; i < v.size(); i ++) {
int temp_num = (cur % mul) * pow(10, k - 2) + v[i];
cout << "temp_num " << temp_num << endl;
if (ans > temp_num) {
ans = temp_num;
result_pair = {i - k + 1, i};
}
cur = temp_num;
}
return result_pair;
}
int main() {
vector<int> v = {6,3,2,4,2,6,8,9};
auto result = lexographically_smallest(v, 3) ;
cout << "indices " << result.first << " " << result.second << endl;
return 0;
}
```

The problem can be solved using a deque or a stack. I am taking a deque here. The idea is to maintain a deque and elements in the deque will hold lexicographically smallest, subsequence till that point of time. The incoming element ll keep popping the elements from the back of the until it is greater than the last element of deque and number of remaining elements + number of elements currently in the deque are >= k

```
vector<int> smallestLexo(vector<int> s, int k) {
deque<int> dq;
for(int i = 0; i < s.size(); i++) {
while(!dq.empty() && s[i] < dq.back() && (dq.size() + (s.size() - i - 1)) >= k) {
dq.pop_back();
}
if(dq.size() < k) {
dq.push_back(s[i]);
}
}
return vector<int> (dq.begin(), dq.end());
}
```

I feel this question can be solved by stack. once we found previous element in the stack is larger than current element, than pop out

- lixx3527 July 09, 2019