0

Suppose we have an array A of size n, there are n unsorted floating point numbers. We want to find a contiguous subarray B such that B sums to an integer. Suppose we can use floor function at cost of O(1). Note that we need to return B if such B exists. My idea:

rsum = running sum of A(i.e. rsum[i]=A[1]+A[2]+...+A[i])
for i from 1 to n:
   for j from i to n:
      e = rsum[j]-rsum[i]+A[i]
      if e==floor(e)
         return A[i....j]
return "no such subarray"

This is an O(n^2) algorithm, is there a way to do that in o(n^2)?

1 Answer 1

2

If we ignore floating point calculation errors, then we can put fractional parts of running sums into a map and check whether the same fraction exists twice - (close to) O(n) approach.

Considering precision issues, we can sort fractions (or put them into sorted container like RB tree) and get the smallest difference - O(nlogn) approach

Sign up to request clarification or add additional context in comments.

2 Comments

A map is not properly O(1) insertion time, and so is not overall O(n) for inserting all the elements and checking for a duplicate.
Yes, I know, but O(1) is typical time and it is usually used for rough estimation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.