F5 Networks

  www.f5.com
  www.f5.com

Interview Question

Senior Software Developer UI Interview Seattle, WA

Given an array & a value x, find if the array contains any

  alues whoes sum = x
Answer

Interview Answer

2 Answers

1

def has_sum( l, v ):
    # assuming more than 2 elements
    for i in range( len(l) ):
        _v = v - l[i]
        _l = l[0:i] + l[i+1:]
        if _v in _l :
            return True
    return False

Nick on Aug 28, 2012
0

#include <vector>
#include <algorithm>

using namespace std;

bool findIfSum(const vector<int> &x, const int val)
{
    vector<int>y = x;
    sort(begin(y), end(y));

    for (auto i = y.begin(); i != y.end(); ++i)
    {
        int diff = val - *i;
        if (diff < 0) return false;
        if (binary_search (i, y.end(), diff)) return true;
    }
    return false;
}

C++ answer on Jan 21, 2014

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up