Skip to content

Conversation

@akshay4121
Copy link

No description provided.

@super30admin
Copy link
Owner

Strengths:

  • You have implemented an optimal solution with O(n) time complexity, which is better than the brute-force O(n^2) approach.
  • The logic is clear: you check for the complement and store the current element and its index in the map.

Areas for Improvement:

  • Remember to import necessary classes. In this case, you need to add import java.util.HashMap; at the top of your file.
  • While the problem states there is exactly one solution, it's a good habit to ensure your code is robust. However, returning an empty array is acceptable here.
  • Consider removing unnecessary blank lines to make the code more concise and readable.
  • You might want to add a comment explaining the approach briefly, though the code is self-explanatory.

Example of improved code:

import java.util.HashMap;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { i, map.get(complement) };
            }
            map.put(nums[i], i);
        }
        return new int[] {};
    }
}

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants