| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FindMissingAndRepeatedValues; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindMissingAndRepeatedValuesMath : IFindMissingAndRepeatedValues |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="grid"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int[] FindMissingAndRepeatedValues(int[][] grid) |
| 2 | 24 | | { |
| 2 | 25 | | var n = grid.Length * grid.Length; |
| | 26 | |
|
| 2 | 27 | | var expectedSum = (long)n * (n + 1) / 2; |
| 2 | 28 | | var expectedSumSquares = (long)n * (n + 1) * ((2 * n) + 1) / 6; |
| | 29 | |
|
| 2 | 30 | | long actualSum = 0; |
| 2 | 31 | | long actualSumSquares = 0; |
| | 32 | |
|
| 16 | 33 | | foreach (var row in grid) |
| 5 | 34 | | { |
| 41 | 35 | | foreach (var num in row) |
| 13 | 36 | | { |
| 13 | 37 | | actualSum += num; |
| 13 | 38 | | actualSumSquares += (long)num * num; |
| 13 | 39 | | } |
| 5 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | var diff = expectedSum - actualSum; |
| 2 | 43 | | var sumDiff = (expectedSumSquares - actualSumSquares) / diff; |
| | 44 | |
|
| 2 | 45 | | var missingNumber = (int)((diff + sumDiff) / 2); |
| 2 | 46 | | var repeatedNumber = (int)(sumDiff - missingNumber); |
| | 47 | |
|
| 2 | 48 | | return [repeatedNumber, missingNumber]; |
| 2 | 49 | | } |
| | 50 | | } |