Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Anudorannador/41182ad89c133841a2aa99f7cf03eba3 to your computer and use it in GitHub Desktop.
Save Anudorannador/41182ad89c133841a2aa99f7cf03eba3 to your computer and use it in GitHub Desktop.
#
# @lc app=leetcode id=2905 lang=python3
#
# [2905] Find Indices With Index and Value Difference II
#
from typing import List
# @lc code=start
class Solution:
def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:
lmax_idx, lmin_idx = 0, 0
if len(nums) <= indexDifference:
return [-1, -1]
for right, value in enumerate(nums[indexDifference:], start=indexDifference):
left = right - indexDifference
lmax_idx = left if nums[left] > nums[lmax_idx] else lmax_idx
lmin_idx = left if nums[left] < nums[lmin_idx] else lmin_idx
if abs(value - nums[lmin_idx]) >= valueDifference:
return [lmin_idx, right]
if abs(nums[lmax_idx] - value) >= valueDifference:
return [lmax_idx, right]
return [-1, -1]
# @lc code=end
if __name__ == "__main__":
test_cases = [
{"nums": [7, 6, 3, 5, 9, 5], "indexDifference": 2, "valueDifference": 6, "expected": [2, 4]},
{"nums": [8, 0], "indexDifference": 1, "valueDifference": 7, "expected": [0, 1]},
{"nums": [1], "indexDifference": 1, "valueDifference": 0, "expected": [-1, -1]},
{"nums": [5, 1, 4, 1], "indexDifference": 2, "valueDifference": 4, "expected": [0, 3]},
{"nums": [2, 1], "indexDifference": 0, "valueDifference": 0, "expected": [0, 0]},
{"nums": [1, 2, 3], "indexDifference": 2, "valueDifference": 4, "expected": [-1, -1]},
]
for i, case in enumerate(test_cases):
sol = Solution()
result = sol.findIndices(case["nums"], case["indexDifference"], case["valueDifference"])
assert result == case["expected"], f"Test case {i + 1} failed: expected {case['expected']}, got {result}"
print("All test cases passed!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment