Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find a sorted subsequence of size 3 in linear time in Pytho
Given an array of N numbers, we need to find three elements such that A[i] where i (an increasing subsequence of size 3) in linear O(n) time. If multiple triplets exist, we return any one of them.
For example, if the input is [13, 12, 11, 6, 7, 3, 31], the output will be (6, 7, 31).
Algorithm Approach
We use two auxiliary arrays to track potential elements ?
- smaller[] − For each position i, stores the index of the smallest element to the left that is smaller than A[i]
- greater[] − For each position i, stores the index of the largest element to the right that is greater than A[i]
Step-by-Step Process
- Create
smaller[]array by scanning left to right, tracking the minimum element seen so far - Create
greater[]array by scanning right to left, tracking the maximum element seen so far - Find any position i where both
smaller[i]andgreater[i]are valid (not -1) - Return the triplet:
A[smaller[i]], A[i], A[greater[i]]
Implementation
def find_inc_seq(A):
n = len(A)
maximum = n - 1
minimum = 0
# Array to store index of smaller element to the left
smaller = [0] * n
smaller[0] = -1
for i in range(1, n):
if A[i] <= A[minimum]:
minimum = i
smaller[i] = -1
else:
smaller[i] = minimum
# Array to store index of greater element to the right
greater = [0] * n
greater[n-1] = -1
for i in range(n-2, -1, -1):
if A[i] >= A[maximum]:
maximum = i
greater[i] = -1
else:
greater[i] = maximum
# Find the triplet
for i in range(n):
if smaller[i] != -1 and greater[i] != -1:
return A[smaller[i]], A[i], A[greater[i]]
return "No increasing subsequence found"
# Test the function
arr = [13, 12, 11, 6, 7, 3, 31]
result = find_inc_seq(arr)
print(f"Input: {arr}")
print(f"Output: {result}")
Input: [13, 12, 11, 6, 7, 3, 31] Output: (6, 7, 31)
How It Works
For the array [13, 12, 11, 6, 7, 3, 31] ?
-
smaller[] becomes
[-1, -1, -1, -1, 3, -1, 5](index 3 has value 6, index 5 has value 3) -
greater[] becomes
[6, 6, 6, 6, 6, 6, -1](index 6 has value 31) - At position 4 (value 7): smaller[4] = 3 and greater[4] = 6
- Triplet: A[3]=6, A[4]=7, A[6]=31 ? (6, 7, 31)
Time and Space Complexity
- Time Complexity: O(n) - three separate linear scans
- Space Complexity: O(n) - two auxiliary arrays of size n
Conclusion
This algorithm efficiently finds an increasing subsequence of size 3 in linear time using two auxiliary arrays to track potential smaller and greater elements. The approach ensures O(n) time complexity by making only three passes through the array.
Advertisements
