An OOP Approach to Solving the Famous Two Sum Algorithmic Problem

How to Solve the Two Sum Problem using an Object Oriented Programming Approach?

An OOP Approach to Solving the Famous Two Sum Algorithmic Problem
Photo by Danial Igdery / Unsplash

Problem Statement

Here's the description of the Two Sum problem:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Example

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

My Solution

The trick part is here to return the indices. Therefore, you want a way to keep this data throughout the problem.

Thinking in terms of data structures, I use List as it's mutable. As a result, I don't need to keep track of which element we are currently looping.

I build the Class structure based on the final output I want.

Bonus: I also override the ToString method, which greatly helps to debug.

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        var item = new Item();
        var list = nums.ToList();
        item.firstValue = list.First();
        item.firstIndex = 0;
        list.RemoveAt(0);

        var counter = 0;
        while (list.Any())
        {
            
            var value = list.Where(x => item.firstValue + x == target);
            if (value.Any())
            {
                item.secondValue = value.FirstOrDefault();
                item.secondIndex = nums.ToList().LastIndexOf(item.secondValue);
                return item.ToResult();
            }
            else 
            {
                item.firstValue = list.FirstOrDefault();
                item.firstIndex = nums.ToList().IndexOf(item.firstValue);
                list.RemoveAt(0);
            }
        }

        return item.ToResult();
    }
}

public class Item
{
    public int firstValue;
    public int firstIndex;
    public int secondValue;
    public int secondIndex;

    public int[] ToResult()
    {
        return new int[] { this.firstIndex, this.secondIndex };
    }

    public override String ToString()
    {
        return $"First Value - First Index: {this.firstValue} - {this.firstIndex} --- Second Value - Second Index : {this.secondValue} - {this.secondIndex}";
    }
}

I usually use CodeWars to sharpen my programming skills but lately, I'm also been experimenting with LeetCode.


Source: