Find a pair of elements from an array whose sum equals a given number?

Some notes about the solution :

  • We iterate only once through the array --> O(n) time
  • Insertion and lookup time in Hash is O(1).
  • Overall time is O(n), although it uses extra space in terms of hash.


    								package com.mindclues.Array;;
    
    /**
     *
     * @author Mindclues
     */
    import java.util.HashMap;
    import java.util.Map;
    
    public class ArrayPairSum {
    
        public static void main(String[] args) {
    
            int[] a = {2, 45, 7, 3, 5, 1, 8, 9};
            printSumPairs(a, 10);
    
        }
    
        public static void printSumPairs(int[] input, int k) {
            Map pairs = new HashMap();
    
            for (int i = 0; i < input.length; i++) {
    
                if (pairs.containsKey(input[i])) {
                    System.out.println(input[i] + ", " + pairs.get(input[i]));
                } else {
                    pairs.put(k - input[i], input[i]);
    
                }
            }
    
        }
    }
    							

    								Output-
    3, 7
    8, 2
    9, 1
    							
  • Related Articles

    post a comment