Directi Interview Question for Software Engineer / Developers


Country: India
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
1
of 3 vote

Consider the following buckets: (0..0.5), [0.5..1), [1..2), [2..inf).
Obviously, we ignore numbers in [2..inf).

Now basically we need to treat all cases of choosing 3 numbers from the 3 buckets.

We only need to look at the following cases (the other cases are "worse" or are covered by these):
1. If possible, choose the smallest element from bucket [1..2) => for the 2nd and 3rd we need to take the smallest 2 elements available. If sum < 2 then return true.

2. If possible, choose the two smallest elements from bucket [0.5 .. 1) => for the 3rd we need to take the smallest element available. If sum < 2 then return true;

3. If possible, choose the highest element from bucket [0.5 .. 1) => if possible, for the 2nd and 3rd take the highest and the second highest from bucket (0 .. 0.5). If sum > 1 then return true.

4. If possible, choose the highest 3 elements from bucket (0..0.5). If sum > 1 then return true.

If none of the cases above found a solution then return false.

Space complexity: O(1), you don't need to explicitly store numbers in buckets.
Time complexity: each operation (e.g.: find smallest element from bucket [1..2), etc.) can be done in O(N). There is a constant number of these operations => overall complexity O(N)

LATER EDIT:

Since the answer was down-graded without any question or explanation why it would be wrong, here is the actual code and the associated tests. Hopefully I didn't forget any relevant test case.

The code could be optimized more and be more condensed, but I tried to make it as clear as possible (regarding to the explanations above and the space and time requirements).

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

const float INF = 1000;

bool inInterval(float x, float st, float end) { return x >= st && x < end; }

bool findFirstSmallest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    res = INF;
    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            res = min(res, a[i]);
        }

    return found >= 1;
}

bool findFirstHighest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    res = -INF;
    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            res = max(res, a[i]);
        }

    return found >= 1;
}

bool findSecondSmallest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    float first = INF, second = INF;

    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            if (a[i] <= first) {
                second = first;
                first = a[i];
            } else if (a[i] <= second)
                second = a[i];
        }

    res = second;
    return found >= 2;
}

bool findSecondHighest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    float first = -INF, second = -INF;

    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            if (a[i] >= first) {
                second = first;
                first = a[i];
            } else if (a[i] >= second)
                second  = a[i];
        }

    res = second;
    return found >= 2;
}

bool findThirdSmallest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    float first = INF, second = INF, third = INF;

    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            if (a[i] <= first) {
                third = second;
                second = first;
                first = a[i];
            } else if (a[i] <= second) {
                third = second;
                second  = a[i];
            } else if (a[i] <= third)
                third = a[i];
        }

    res = third;
    return found >= 3;
}

bool findThirdHighest(const vector<float>& a, float start, float end, float &res) {
    int found = 0;

    float first = -INF, second = -INF, third = -INF;

    for (int i = 0; i < a.size(); ++i)
        if (inInterval(a[i], start, end)) {
            ++found;
            if (a[i] >= first) {
                third = second;
                second = first;
                first = a[i];
            } else if (a[i] >= second) {
                third = second;
                second  = a[i];
            } else if (a[i] >= third)
                third = a[i];
        }

    res = third;
    return found >= 3;
}

bool solve(const vector<float>& a, float& x, float &y, float& z) {
   if (findFirstSmallest(a, 1, 2, x) && 
       findFirstSmallest(a, 0, 1, y) &&
       findSecondSmallest(a, 0, 1, z))
        if (x + y + z < 2) return true;

   if (findFirstSmallest(a, 0.5, 1, x) &&
       findSecondSmallest(a, 0.5, 1, y) &&
       (findFirstSmallest(a, 0, 0.5, z) || findThirdSmallest(a, 0.5, 1, z) ))
        if (x + y + z < 2) return true;

   if (findFirstSmallest(a, 0.5, 1, x) &&
       findFirstHighest(a, 0, 0.5, y) &&
       findSecondHighest(a, 0, 0.5, z))
        if (x + y + z >= 1) return true;

   if (findFirstHighest(a, 0, 0.5, x) &&
       findSecondHighest(a, 0, 0.5, y) &&
       findThirdHighest(a, 0, 0.5, z))
        if (x + y + z >= 1) return true;

   return false;
}

void test(const vector<float>& a) {
    cout << "Test: ";
    copy(a.begin(), a.end(), ostream_iterator<float>(cout, " "));
    cout << endl;

    float x, y, z;
    if (solve(a, x, y, z))
        cout << "Solution: " << x << " " << y << " " << z << endl;
    else
        cout << "Solution not found!" << endl;

    cout << endl;
}

#define arrSize(a) (sizeof(a) / sizeof(a[0]))

int main() {
    float test1[] = {0.1, 0.2, 0.2, 0.3, 2.0, 3.0};
    test(vector<float>(test1, test1 + arrSize(test1)));

    float test2[] = {0.1, 0.3, 0.3, 0.4, 2.0, 3.0};
    test(vector<float>(test2, test2 + arrSize(test2)));

    float test3[] = {0.1, 0.1, 0.2, 0.6, 2.0, 3.0};
    test(vector<float>(test3, test3 + arrSize(test3)));

    float test4[] = {0.5, 0.6, 0.6, 2.0, 3.0};
    test(vector<float>(test4, test4 + arrSize(test4)));

    float test5[] = {0.6, 0.6, 2.0, 3.0};
    test(vector<float>(test5, test5 + arrSize(test5)));

    float test6[] = {0.6, 0.6, 1.0, 2.0, 3.0};
    test(vector<float>(test6, test6 + arrSize(test6)));

    float test7[] = {0.1, 0.2, 0.5, 1.0, 2.0, 3.0};
    test(vector<float>(test7, test7 + arrSize(test7)));

    float test8[] = {0.1, 0.7, 0.6, 1.0, 2.0, 3.0};
    test(vector<float>(test8, test8 + arrSize(test8)));

    float test9[] = {0.5, 0.5, 0.6, 1.0, 2.0, 3.0};
    test(vector<float>(test9, test9 + arrSize(test8)));

    float test10[] = {1.6, 1.2, 1.0, 2.0, 3.0};
    test(vector<float>(test10, test10 + arrSize(test10)));

    return 0;
}

- cristian.botau February 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

how you are sorting and making the bucet in range in linear time..
?
Can you elaborate that

- sjain February 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I am not sorting and I'm not actually making any bucket. The buckets are used for algorithm explanation.

You basically need the following operations:
- find x - the smallest element in input vector that (x >= 1 and x < 2) - easily done in O(N) with a simple pass through the array
- take the smallest element & second smallest element from the input array (and ignore the first element from triple) - doable in O(N)
- find x the highest element s.t. (x >= 0.5 and x < 1) - O(N)
- etc.

To generalize, the algorithm uses operations like: find the first/second lowest/highest element which lies in the interval [a..b). These operations are doable in O(N).

- cristian.botau February 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I've updated answer to contain the program and tests used for the program. Hopefully I didn't leave any important test cases out. If you find any failing input data please post it ;)

- cristian.botau July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

@anonymous - Yup he used those constraints
@max - There must be a solution present if he asked

- abbi031892 February 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 4 votes

"There must be a solution"... why? Was he God? Looks more like an idiot. (See the comment about 3SUM).

- Anonymous February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

public static Boolean funct(double[] arr) {
Integer count =0;
for(int i=0;i<arr.length; i++){
if(arr[i] < 2 ){
count++;
for(int j=i+1;j<arr.length; j++){
if(arr[j] < 2 && arr[i]+arr[j]< 2.0){
count++;
for(int x=j+1;x<arr.length; x++){
if(arr[i] < 2 ){
if(arr[i]+arr[j] + arr[x] <2.0 && arr[i]+arr[j] + arr[x] >= 1.0&& count ==2 ){
System.out.println(arr[i]);
System.out.println(arr[j]);
System.out.println(arr[x]);
x=arr.length;
return true;
}
}
}
j=arr.length;
}
}
i=arr.length;

}
}
return false;
}

//***************TEST EXAMPLE********************
public static void main(String[] args) {
double[] x={1,1.1,0.3,3,2,1,1,2,0.2,0.2,6,7};
Boolean b;
b=funct(x);
if(b == false)
System.out.println("Unable to find the sum of the triplet is in the range (1, 2)");

}
}

- arpitg February 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

My understanding, if there are real numbers the function should be:

boolean funct(double[] arr) or float.

- m@}{ February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks

updated the code to work with double

- arpitg February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

How is it O(n) ??

- abbi031892 February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

if you notice., j=arr.length;
i=arr.length;

These 2 commands will ensure that this code will not run more than O(n)

- arpitg February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I might be wrong too.......please repost the code with whitespaces....will help to understand better

- abbi031892 February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

what will your code will do for {1.9,0.2,0.3,0.4} ?

- abbi031892 February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Just ran the code
Output: Unable to find the sum of the triplet is in the range (1, 2)

- arpitg February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

last check ....... {1.9,0.2,0.5,0.36}

- abbi031892 February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

so the algorithm is trying a 3 pairs of numbers in the array - right? Imagine you have 10 elements in the array. How many times do you consider the last element of the array?

Consider adding iteration counters to help you see why this solution is very far from O(N).

- Anonymous February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Anonymous on February 17, 2013
I have put iterations in and it never goes above o(n).. but if you want then replace j=arr.length; & i=arr.length with "return false"

- arpitg February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I hadn't noticed the early returns. In that case your solution is not correct - consider {0, 0, 0.9, 0, 0.9} (or the example above {1.9,0.2,0.5,0.36}).

- Anonymous February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And if you don't want to see zeroes, replace zero by 0.00001.

- Anonymous February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

i was just responding to your incorrect comments about the complexity.
i know that.. {1.9,0.2,0.5,0.36}..I will work on the fix later

- Anonymous February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good luck!

- Anonymous February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It doesn't find solution with input array = {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.4, 0.4, 0.4}.

- Bob February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

can you elaborate, how this method takes O(n), its goin to take O(n^3)

- sjain February 21, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

num=[float(x) for x in raw_input().split(' ')]
a=[x for x in num if 0< x < 1]
b=[x for x in num if 1<= x < 2]

a.sort()
min3a=a[:3]
max3a=a[len(a)-3:]
	
if len(a)>=3:
	if 2<=sum(min3a):
		print None
	elif 1 < sum(min3a) < 2:
		print min3a
if 1<sum(max3a):
	for i in range(0,4):
		if 1<sum(min3a[:i]+max[i:])<2:
			print min3a[:i]+max[i:]
if len(b)>=1 and len(a)>=2:
	if 1<sum(min3a[0:2]+[min(b)])<2:
		print min3a[0:2]+[min(b)]

- harshit.knit November 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Is the last statement was really in the question?

- Anonymous February 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Take a integer variable and set last 3 LSB for each 0 obtained, and 4-6 LSB for each 1.
Then check if those bits are set and if yes return true.

BOOL findtriplet(int* arr)
{
int count = 0;
while(arr[i] != '\0')
{
if(a[i] == 0)
count = (count | 1) << 1;
if(a[i] == 1)
count = ((count&7) | ((count | 8) << 1));
if((count & 7) | (count & 56))
return true;
}
return false
}

- Anonymous February 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I have said positive .....that means no '0' in it ....

- abbi031892 February 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

can you elaborate on logic??

- Anonymous February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

This is 3sum-hard problem, so can't be solved in O(N) time and O(1) space.

- m@}{ February 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is not 3SUM-hard. The data has other characteristics which might make the problem solvable in linear time:
- numbers are positive
- sum must lie in an interval

Check my answer on how we can "exploit" these relaxed requirements in order to obtain a linear algorithm.

- cristian.botau February 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

I think we can do it in nlogn by first sorting it, then check if a[i-1]+a[i]+a[i+1] is in range(1,2) from i=(1 to lastIndex-1)

- Yijie Li February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This wont work either,you are just checking for consecutive triplets..ex {0.1,0.2,0.3,0.4,1.4}.your solution will return false but there exists a triplet i.e {0.1+0.4+1.4=1.9<2}

- Gitesh Gupta February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Gitesh: After Shorting checking consecutive triplets is OK. Is nt it??

- techieDeep February 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

it is O(n) requirement ...how you people thinking of sorting ?

- abbi031892 February 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 votes

what if array contains negative numbers.

- sjain July 10, 2013 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 votes

Then you would have to check all combinations of triplets and it can not be done in O(n) time. But in this case, question states that the array contains only positive numbers and my solution is correct.

- thelineofcode July 10, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

your solution fails for this combination
[0.001, 0.002,0.004, 1.0 , 2.0, 0.3 , 0.3 , 0.5 , 0.1 ,0.01 , 0.01 , 0.7, 1.0]

- sahild July 15, 2013 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More