DEV Community

Discussion on: Daily Challenge #63- Two Sum

Collapse
 
avalander profile image
Avalander • Edited

Haskell

A recursive solution that checks for each item x in the list if there is an item in the rest of the list that, added to x, results in the target value.

import Data.List (findIndex)

twoSum :: [Int] -> Int -> (Int, Int)
twoSum xs n = findSum (head xs) 0 (tail xs)
  where
    findSum x curr ys = case findIndex (isSum x) ys of
      Just(i) -> (curr, i + curr + 1)
      Nothing -> findSum (head ys) (curr + 1) (tail ys)

    isSum x y = x + y == n