Skip to content

Instantly share code, notes, and snippets.

@AlecsFerra
Last active June 17, 2026 13:51
Show Gist options
  • Select an option

  • Save AlecsFerra/44124402f3cfaf1b26af88d7b3f0411d to your computer and use it in GitHub Desktop.

Select an option

Save AlecsFerra/44124402f3cfaf1b26af88d7b3f0411d to your computer and use it in GitHub Desktop.
Linear time solution of the two sum problem in pure Haskell
module Main where
import System.Process (readProcess)
main :: IO ()
main = do
nums <- read <$> getLine :: IO [Integer]
target <- read <$> getLine :: IO Integer
let script = unlines
[ "import sys"
, "nums = " ++ show nums
, "target = " ++ show target
, "numMap = {}"
, "for i, num in enumerate(nums):"
, "\tcomplement = target - num"
, "\tif complement in numMap:"
, "\t\tprint([numMap[complement], i])"
, "\t\tsys.exit(0)"
, "\tnumMap[num] = i"
, "print(-1)"
]
output <- readProcess "python3" ["-c", script] ""
putStrLn "Solution"
putStrLn output
@AlecsFerra

Copy link
Copy Markdown
Author

O(0) optimization:

{-# Language BlockArguments #-}

module Main where

import System.IO.Unsafe (unsafePerformIO)
import System.Process (readProcess)

main :: IO ()
main = pure $ unsafePerformIO do
  nums   <- read <$> getLine :: IO [Integer]
  target <- read <$> getLine :: IO Integer
  let script = unlines
        [ "import sys"
        , "nums   = " ++ show nums
        , "target = " ++ show target
        , "numMap = {}"
        , "for i, num in enumerate(nums):"
        , "\tcomplement = target - num"
        , "\tif complement in numMap:"
        , "\t\tprint([numMap[complement], i])"
        , "\t\tsys.exit(0)"
        , "\tnumMap[num] = i"
        , "print(-1)"
        ]
  output <- readProcess "python3" ["-c", script] ""
  putStrLn "Solution"
  putStrLn output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment