Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/find-missing-and-repeating2512/1
Missing And Repeating
Difficulty: Easy Accuracy: 24.83%
Given an unsorted array arr[] of size n, containing elements from the range 1 to n, it is known that one number in this range is missing, and another number occurs twice in the array, find both the duplicate number and the missing number.
Examples:
Input: arr[] = [2, 2]
Output: [2, 1]
Explanation: Repeating number is 2 and the missing number is 1.
Input: arr[] = [1, 3, 3]
Output: [3, 2]
Explanation: Repeating number is 3 and the missing number is 2.
Input: arr[] = [4, 3, 6, 2, 1, 1]
Output: [1, 5]
Explanation: Repeating number is 1 and the missing number is 5.
Constraints:
2 β€ n β€ 106
1 β€ arr[i] β€ n
Solution:
class Solution:
def findTwoElement(self, arr):
n = len(arr)
S = sum(arr)
S_n = n*(n+1)//2
Sq = sum(x*x for x in arr)
Sq_n = n*(n+1)*(2*n+1)//6
diff = S - S_n
sq_diff = Sq - Sq_n
sum_xy = sq_diff // diff
x = (diff + sum_xy) // 2
y = x - diff
return [x, y]
Top comments (0)