If statement condition error missing value in two sum problem?

Viewed 49

I am working through practice problems for interviews and ran into a problem with an "if" statement that I do not know how to solve. The practice question is as follows:

Two sum. Given an array and a number N, return True if there are numbers A, B in the array such that A + B = N. Otherwise, return False.

Example:

[1, 2, 3, 4], 5 ⇒ True

[3, 4, 6], 6 ⇒ False

My code (below) returns the following error: Error in if (i + A[j] == N) { : missing value where TRUE/FALSE needed

fun = function(A,N) {
  flag = FALSE
  for (i in A) {
    for (j in i:length(A)) {
      if (i + A[j] == N) {
        flag = TRUE
      } 
    }
  }
  return(flag)
}

fun(as.integer(c(3, 4, 6)),6)
2 Answers

A vectorized solution without loops:

sumN <- function(A,N){
  any(colSums(combn(A,2))==N)
}

sumN(c(1,2,3,4),5)
[1] TRUE

sumN(c(3,4,6),6)
[1] FALSE

The problem in your code is your second for loop should be 1:length(A) not i:length(A).

fun <- function(A, N){
  flag = FALSE
  for (i in A) {
    for (j in 1:length(A)) {
      if (i + A[j] == N) {
        flag = TRUE
      } 
    }
  }
  
  return(flag)
}

fun(as.integer(c(3, 4, 6)), 6)
[1] TRUE

When i equals 4 and length(A) is fixed at 3 your posted code was sequencing 4:3. j will take on a value of 4 and then when you try to index A[4] you will get NA.


Update

To avoid double counting an element with your code you could do this:

fun <- function(A, N){
  flag = FALSE
  for (i in A) {
    for (j in A[A != i]) { # select elements of A that aren't equal to i
      if (i + j == N) {
        flag = TRUE
      } 
    }
  }
  
  return(flag)
}

Though this isn't super efficient because it will double check some pairs twice.

Related