Easy csharp

Two Sum — indices for target 8 #37

Problem

Given [1, 2, 3, 4, 5] and target 8, print the two indices (0-based) separated by space.

Hints
  • Store value → index in Dictionary

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] nums = { 1, 2, 3, 4, 5 };
        int target = 8;
        var map = new Dictionary<int, int>();
        for (int j = 0; j < nums.Length; j++) {
            int need = target - nums[j];
            if (map.ContainsKey(need)) { Console.WriteLine(map[need] + " " + j); return; }
            map[nums[j]] = j;
        }
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Classic hash-map two sum — O(n) time.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details