Accepted Java Time Complexity: O(n), Space Complexity: O(n)

  • 0

    I solve this problem by using Hash Map and try to minimize th time and space complexity and before this solution I tried to solve it by simple two for loop but it didn't make any sense as it was not efficient

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int arr[] = new int[2];
            Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
            for(int i = 0; i < nums.length; ++i) {
                mp.put(nums[i], i);
            for(int j = 0; j < nums.length; ++j) {
                int comp = target - nums[j];
                if(mp.containsKey(comp)) {
                    int val = mp.get(comp);
                    if(val == j) {
                    else {
                        arr[0] = j;
                        arr[1] = val;
            return arr; 

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.