Last active
June 17, 2026 13:51
-
-
Save AlecsFerra/44124402f3cfaf1b26af88d7b3f0411d to your computer and use it in GitHub Desktop.
Linear time solution of the two sum problem in pure Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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