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 smallest pair sum where distance is not consecutive in Python
When working with arrays, we sometimes need to find pairs of elements that satisfy specific distance constraints. In this problem, we want to find the smallest sum of two elements where their indices are not consecutive (distance greater than 1).
Problem Understanding
Given a list of numbers, we need to find any pair of indices (i, j) where i < j and j - i > 1, then return the smallest possible sum. This means we cannot select adjacent elements.
For example, with nums = [3, 4, 2, 2, 4], we can select values 3 and 2 (indices 0 and 2) for a sum of 5. We cannot select the two 2's because they are adjacent.
Algorithm Approach
The solution uses a greedy approach ?
- n := size of nums
- min_seen := nums[0] (track minimum element seen so far)
- ans := infinity (stores minimum pair sum)
- for i in range 2 to n - 1, do
- ans := minimum of ans and (min_seen + nums[i])
- min_seen := minimum of min_seen and nums[i - 1]
- return ans
Implementation
def solve(nums):
n = len(nums)
min_seen = nums[0]
ans = float("inf")
for i in range(2, n):
ans = min(ans, min_seen + nums[i])
min_seen = min(min_seen, nums[i - 1])
return ans
# Test the function
nums = [3, 4, 2, 2, 4]
result = solve(nums)
print(f"Input: {nums}")
print(f"Smallest non-consecutive pair sum: {result}")
Input: [3, 4, 2, 2, 4] Smallest non-consecutive pair sum: 5
How It Works
The algorithm maintains min_seen as the minimum element encountered so far that can be paired with the current element. At each position i (starting from index 2), we ?
- Calculate potential sum:
min_seen + nums[i] - Update our answer if this sum is smaller
- Update
min_seento includenums[i-1]for future iterations
Step-by-Step Trace
def solve_with_trace(nums):
n = len(nums)
min_seen = nums[0]
ans = float("inf")
print(f"nums = {nums}")
print(f"Initial: min_seen = {min_seen}")
for i in range(2, n):
current_sum = min_seen + nums[i]
ans = min(ans, current_sum)
print(f"i={i}: nums[i]={nums[i]}, min_seen={min_seen}, sum={current_sum}, ans={ans}")
min_seen = min(min_seen, nums[i - 1])
print(f" Updated min_seen = {min_seen}")
return ans
nums = [3, 4, 2, 2, 4]
result = solve_with_trace(nums)
print(f"Final result: {result}")
nums = [3, 4, 2, 2, 4] Initial: min_seen = 3 i=2: nums[i]=2, min_seen=3, sum=5, ans=5 Updated min_seen = 3 i=3: nums[i]=2, min_seen=3, sum=5, ans=5 Updated min_seen = 2 i=4: nums[i]=4, min_seen=2, sum=6, ans=5 Updated min_seen = 2 Final result: 5
Conclusion
This greedy algorithm efficiently finds the smallest non-consecutive pair sum in O(n) time complexity. The key insight is maintaining the minimum element seen so far that can form a valid pair with future elements.
