Two-Sum Problem

Added: 2025-09-13 08:29:37

Question Image

Two-Sum Problem

Answer

✏️ Edit
def solve():
    # Step 1: Input
    n, x = map(int, input().split())
    arr = list(map(int, input().split()))
    
    # Step 2: Dictionary to store {value: index}
    seen = {}
    
    # Step 3: Iterate through array
    for i in range(n):
        needed = x - arr[i]
        if needed in seen:
            idx1 = seen[needed] + 1
            idx2 = i + 1
            # Ensure smaller index comes first
            if idx1 < idx2:
                print(idx1, idx2)
            else:
                print(idx2, idx1)
            return
        seen[arr[i]] = i
    
    # Step 4: No solution
    print("IMPOSSIBLE")


# Run
solve()