Skip to content

Instantly share code, notes, and snippets.

@thecaralice
Created April 14, 2022 22:01
Show Gist options
  • Save thecaralice/7b77625824e9a9b6bfbb4ad2669b561a to your computer and use it in GitHub Desktop.
Save thecaralice/7b77625824e9a9b6bfbb4ad2669b561a to your computer and use it in GitHub Desktop.
Given an integer array `numbers` and an integer `target`, find (`i`, `j`) such that `numbers[i] + numbers[j] == target`
from ast import literal_eval
from collections import deque
from typing import Callable, Iterable
from more_itertools import is_sorted
def solve_sorted(numbers: Iterable[int], target: int) -> tuple[int, int] | None:
values = deque(numbers)
start = 0
while len(values) >= 2:
s = values[0] + values[-1]
if s < target:
values.popleft()
elif s > target:
values.pop()
else:
return start, start + len(values) - 1
return None
def solve_unsorted(numbers: Iterable[int], target: int) -> tuple[int, int] | None:
indices = {v: i for i, v in enumerate(numbers)}
for v, i in indices.items():
co = target - v
co_i = indices.get(co)
if co_i is None:
continue
return i, co_i
return None
def main():
numbers = literal_eval(input("\x1b[1mnumbers\x1b[m = "))
target = literal_eval(input("\x1b[1mtarget\x1b[m = "))
solve: Callable[[Iterable[int], int], tuple[int, int] | None]
if is_sorted(numbers):
print("\x1b[32msorted\x1b[m")
solve = solve_sorted
else:
print("\x1b[31munsorted\x1b[m")
solve = solve_unsorted
print("\x1b[1mResult\x1b[m:", solve(numbers, target))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment