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
Program to find length of longest alternating inequality elements sublist in Python
Given a list of numbers, we need to find the length of the longest sublist where the inequality relation between consecutive numbers alternates between less-than and greater-than operations. The first two numbers can start with either inequality relation.
So, if the input is like nums = [1, 2, 6, 4, 5], then the output will be 4, as the longest alternating inequality sublist is [2, 6, 4, 5] where 2 < 6 > 4 < 5.
Algorithm
To solve this problem, we follow these steps ?
Define a helper function
get_direction()that returns the relationship between two numbersHandle edge case: if list has fewer than 2 elements, return its length
Track the maximum length found, current length, and last direction
Iterate through consecutive pairs, checking if the direction alternates
Update lengths based on whether the pattern continues or breaks
Implementation
class Solution:
def solve(self, nums):
if len(nums) < 2:
return len(nums)
def get_direction(a, b):
return 0 if a == b else -1 if a < b else 1
max_length = 1
cur_length = 1
last_direction = 0
for i in range(len(nums) - 1):
direction = get_direction(nums[i], nums[i + 1])
if direction == 0:
cur_length = 1
elif direction == last_direction:
cur_length = 2
else:
cur_length += 1
max_length = max(max_length, cur_length)
last_direction = direction
return max_length
# Test the solution
ob = Solution()
nums = [1, 2, 6, 4, 5]
result = ob.solve(nums)
print(f"Input: {nums}")
print(f"Length of longest alternating sublist: {result}")
Input: [1, 2, 6, 4, 5] Length of longest alternating sublist: 4
How It Works
The algorithm uses a helper function get_direction() that returns ?
0if two numbers are equal-1if the first number is less than the second1if the first number is greater than the second
For each consecutive pair, we check if the direction alternates from the previous pair. If it does, we extend the current sublist. If not, we start a new sublist of length 2.
Additional Example
# Test with different cases
test_cases = [
[1, 3, 2, 4, 3, 5], # Expected: 6 (entire array alternates)
[1, 2, 3, 4], # Expected: 2 (no alternation)
[5, 4, 3, 2, 1], # Expected: 2 (no alternation)
[1, 3, 2, 4, 4, 5] # Expected: 4 (breaks at equal elements)
]
ob = Solution()
for i, nums in enumerate(test_cases, 1):
result = ob.solve(nums)
print(f"Test {i}: {nums} ? {result}")
Test 1: [1, 3, 2, 4, 3, 5] ? 6 Test 2: [1, 2, 3, 4] ? 2 Test 3: [5, 4, 3, 2, 1] ? 2 Test 4: [1, 3, 2, 4, 4, 5] ? 4
Conclusion
This solution efficiently finds the longest alternating inequality sublist in O(n) time complexity. The key insight is tracking the direction changes between consecutive elements and resetting the count when the alternating pattern breaks.
