Two-Sum Problem

Two-Sum Problem

I know I promised last week, but things ended up getting hectic and I didn’t have the time at all. I still do not have the time, but I made a commitment and will meet it! Here’s a two-sum problem to get the ball rolling.

So let’s take a look at a quick problem to get me back into the habit of posting.

Two-Sum Problem

math outside
Wanda Dechant

You are given an array and a target number as inputs and the goal is to find any two numbers in the array that add up to the target. You have to return the indexes of the two numbers in a tuple.

There can be multiple correct answers and for this challenge, there will always be a viable solution.

Source: Leet Code

Example

array = [3,2,1,3] target = 4 can result in (0,2) or (2,3)
Code language: PHP (php)

Solution

Today we’re brute forcing it. We get the first number, check if there exists another number where their sum equals our target and return those two if it is there, otherwise we move on to the next number.

pub fn two_sum(numbers: &[i32], target: i32) -> (usize, usize) {<br> let mut index = 0;<br><br> loop {<br> let counter_part = target - numbers[index];<br> let found = numbers.iter().position(|&x| x == counter_part);<br> match found {<br> <em>Some</em>(value) => {<br> if index != value {<br> return (index, value);<br> }<br> }<br> <em>None </em>=> (),<br> }<br> index += 1<br> }<br>}
Code language: Rust (rust)

Today’s problem taught me, again, the importance of constant practice. I haven’t been coding in Rust for the last month and it shows. I’m rusty as hell. No pun intended.

But it oddly feels good to have done something at least. If you tried this one, let me know on Twitter, @phoexer, happy coding.


Image Credits: math outside by Wanda Dechant used under .