Mark As Completed Discussion

Ready for Pseudo-Code

Armed with this knowledge, we are ready to construct the pseudo-code for an algorithm that solves LIS efficiently.

All we need to do is scan the items of arr one by one, and find their place in LISArray. Because LISArray stores the indices of items of the input array in sorted order, we can use binary search to find the place of arr[i] in LISArray.

The example below shows how LISArray is filled out one by one, when given an element of arr. We also need to keep track of the last filled index of LISArray. We only add a new item to LISArray when the next item of arr is higher than all items that were previously added.

Ready for Pseudo-Code

The final pseudo-code is given below. Note that the algorithm goes through each item of arr exactly once (n items scanned once) and finds their place in LISArray using binary search (O(log n) time). Hence the overall time complexity of this algorithm is O(n log n).

SNIPPET
1Routine: LISFast
2Input: arr of length n
3Output: Largest increasing subsequence within arr
4Intermediate storage: LISArray of size (n+1), initialized to zero
5
61. lastIndex = 1
72. LISArr[lastIndex] = 0
83. for i=1..n
9    a. ind = binary search for index position in LISArr for arr[i]
10    b. LISArr[ind] = i
11    c. if (ind > lastIndex)
12        lastIndex = ind
134. return lastIndex

You can now write efficient code for finding LIS in O(n log(n)) time using the examples and pseudo-code.

Getting the sequence along with the length

Ever wondered how you can get the actual sequence from the given array? We can do this easily by using another array. Try to edit the above solution and solve this one. Finally, see the solution attached.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment