TwoSum: Given an array of integers, return the indices of the two numbers...

This problem is asking for the indices of two numbers in an array that add up to a given target. For example, if the array is [2, 7, 11, 15] and the target is 9, the solution would be [0, 1] because 2 + 7 = 9.

Problem

Given an array of integers, return the indices of the two numbers such that they add up to a specific target.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

This solution is in C#. Our A.I. can create solutions in multiple languages.
by kayakane
using System;
using System.Collections.Generic;

namespace InterviewPreperationGuide.Core.CrackingTheCodingInterview.c1q1 {
    public class Solution {
        public void Init () {
            Console.WriteLine ();
        }

        // Time: O (n)
        // Space: O (n)
        public int[] TwoSum (int[] nums, int target) {
            int[] result = new int[2];

            if (nums != null && nums.Length > 0) {
                Dictionary<int, int> map = new Dictionary<int, int> ();

                for (int i = 0; i < nums.Length; i++) {
                    if (map.ContainsKey (target - nums[i])) {
                        result[0] = map[target - nums[i]];
                        result[1] = i;
                        break;
                    } else {
                        if (!map.ContainsKey (nums[i])) {
                            map.Add (nums[i], i);
                        }
                    }
                } }

            return result;
        }
    }
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate's approach is to use a dictionary to store each number in the array and its index. Then, for each number, the candidate checks if the dictionary contains the number needed to sum to the target. If so, the candidate returns the indices of the two numbers. Otherwise, the candidate adds the number to the dictionary.

Evaluated at: 2022-11-25 14:16:08