Homework 1

Homework 1

Hello, my name is Shih-Yen Pan. I am a PhD student in Economics at UMass, Amherst.

In this post, I will introduce the Two Sum problem from LeetCode and a solution using double for loop provided by Pascal Schmidt here. I thought it might be useful to see what for loop looks like in R.

The idea of the problem is, given a list of integers nums and an integer target, to write a function that spits out, if they exist, two different integers in nums that sum up to the target integer.

two_sum <- function(nums, target) {

  for(i in seq_along(nums)) {
    for(j in seq_along(nums)[-length(nums)]) {
      
      sum <- nums[i] + nums[j + 1]
      if(sum == target) {
        
        first <- i
        second <- j + 1
        output <- c(nums[first], nums[second])
        return(output)
        
      }
      
    }
    
  }
  
}

This is what the function two_sum is doing: Starting from the beginning of the vector ‘nums’, for each integer, search the rest of vector using the second for loop. If the two numbers sum up to the target integer, the code returns those two numbers; otherwise, continue doing the same with the next integer in the list.

Example:

nums <- c(1, 2, 3, 5, 6, 9, 11)
target <- 9
two_sum(nums, target)

This should return 3 and 6.

Try it out yourself with different numbers! How can the code be modified to return all the different pairs that sum to the target integer?

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY-NC 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".