Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It seems like we could check for duplicates by multiplying all the numbers n...n+m together, and then comparing that value to the expected product of a sequence with no duplicates <strong>m!/(n-1)!</strong> (note that this assumes it is impossible for a sequence to pass both the expected sum test <strong>and</strong> the expected product test).</p> <p>So adding to <a href="https://stackoverflow.com/revisions/viewmarkup/224981">hazzen's pseudo-code</a>, we have:</p> <pre><code>is_range(int[] nums, int n, int m) { sum_to_m := (m * (m + 1)) / 2 expected_sum := sum_to_m - (n * (n - 1)) / 2 real_sum := sum(nums) expected_product := m! / (n - 1)! real_product := product(nums) return ((real_sum == expected_sum) &amp;&amp; (expected_product == real_product)) </code></pre> <p><br/> <strong>EDIT:</strong> Here's my solution in Java using the Sum of Squares to check for duplicates. It also handles any range (including negative numbers) by shifting the sequence to start at 1.</p> <pre><code>// low must be less than high public boolean isSequence(int[] nums, int low, int high) { int shift = 1 - low; low += shift; high += shift; int sum = 0; int sumSquares = 0; for (int i = 0; i &lt; nums.length; i++) { int num = nums[i] + shift; if (num &lt; low) return false; else if (num &gt; high) return false; sum += num; sumSquares += num * num; } int expectedSum = (high * (high + 1)) / 2; if (sum != expectedSum) return false; int expectedSumSquares = high * (high + 1) * (2 * high + 1) / 6; if (sumSquares != expectedSumSquares) return false; return true; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload