fork download
  1. function twoSum(nums, target) {
  2. const numIndices = {}; // Create an object to store numbers and their indices
  3.  
  4. for (let i = 0; i < nums.length; i++) {
  5. const complement = target - nums[i]; // Calculate the complement of the current number
  6.  
  7. // Check if the complement is already in the object
  8. if (numIndices.hasOwnProperty(complement)) {
  9. // If it is, return the indices of the complement and the current number
  10. return [numIndices[complement], i];
  11. }
  12.  
  13. // Otherwise, store the index of the current number in the object
  14. numIndices[nums[i]] = i;
  15. }
  16.  
  17. // If no solution is found, return an empty array or throw an error
  18. return [];
  19. }
  20.  
  21. // Example usage:
  22. const nums = [2, 7, 11, 15];
  23. const target = 9;
  24. const result = twoSum(nums, target);
  25. console.log(result); // Output: [0, 1]
Success #stdin #stdout 0.02s 25572KB
stdin
Standard input is empty
stdout
function twoSum(nums, target) {
    const numIndices = {}; // Create an object to store numbers and their indices

    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i]; // Calculate the complement of the current number

        // Check if the complement is already in the object
        if (numIndices.hasOwnProperty(complement)) {
            // If it is, return the indices of the complement and the current number
            return [numIndices[complement], i];
        }

        // Otherwise, store the index of the current number in the object
        numIndices[nums[i]] = i;
    }

    // If no solution is found, return an empty array or throw an error
    return [];
}

// Example usage:
const nums = [2, 7, 11, 15];
const target = 9;
const result = twoSum(nums, target);
console.log(result); // Output: [0, 1]