Two Sum in R

Two Sum LeetCode Problem

Given an array of integers and a target, return the index of the two numbers that add to the target.

Assuming:

  • Each input has exactly one solution
  • An element can only be used once
  • You can return the index positions in any order

Two Sum Function

two_sum_for <- function(nums, target){
for(i in 1:length(nums)){
for(j in 1:length(nums)){
if(j == i){ 
next #  If i and j are the same index skip 
}
if (sum(nums[i], nums[j] ) == target) {
first <- i
second <- j
indexes <- c(first,second)
return(indexes)
}}}
}

Example:

  • Integers = (2,7,11,15)
  • Target = 9
> two_sum_for(nums = c(2,7,11,15), target = 9)
[1] 1 2

The function returns the 2 indexes, 1 and 2, which when added equal the target (2 + 7 =9). Remeber R starts counting at 1 unlike other programming languages that start with 0.

Leave a Reply

Your email address will not be published. Required fields are marked *