Intro: As far as I could search, this question wasn't asked in SO yet.
This is an interview question.
I am not even specifically looking for a code solution, any algorithm/pseudocode will work.
The problem: Given an integer array int[] A
and its size N
, find 2 non-subsequent (can't be adjacent in the array) elements with minimal sum. Also the answer must not contain the first or last elements (index 0
and n-1
). Also the solution should be in O(n)
time and space complexity.
E.g. when A = [5, 2, 4, 6, 3, 7]
the answer is 5
, since 2+3=5
.
When A = [1, 2, 3, 3, 2, 1]
the answer is 4
, since 2+2=4
and you can't choose either of the 1
's since the are at the ends of the array.
Attempt: At first I thought that one of the numbers in the solution must be the smallest one in the array (besides the first and last), but this was refuted quickly with the counter-example
A = [4, 2, 1, 2, 4]
-> 4 (2+2)
Then I thought that if I find the 2 smallest numbers (besides the first and last) in the array, the solution will be those two. This obviously quickly failed because I can't choose 2 adjacent numbers, and if I have to choose non-adjacent numbers then this is the very definition of the question :).
Finally I thought, well, I will just find the 3 smallest numbers (besides the first and last) in the array, and the solution will have to be two of those, since two of those have to not be adjacent to each other.
This also failed due to A = [2, 2, 1, 2, 4, 2, 6]
-> 2+1=3
, which seems to work because I will find 2, 1, 2
, but assuming I am finding the 2, 1, 2
in indexes 1, 2, 3
this won't necessarily work (it would if I found specifically the 2
in index 5
but I can't guarantee that unfortunately).
Question: Now I'm stumped, can anyone come up with a solution/idea that works?