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/construct-an-array-from-its-pair-sum-array/1
Construct an array from its pair-sum array
Difficulty: Easy Accuracy: 49.0%
Given a pair-sum array arr[] construct the original array. A pair-sum array for an array is the array that contains sum of all pairs in ordered form, i.e., arr[0] is sum of res[0] and res[1], arr[1] is sum of res[0] and res[2] and so on.
Note: If the size of original array res[] is n, then the size of pair-sum array arr[] would be n * (n -1) /2. We may assume that the pair-sum array arr[] is appropriate in size.
Note that, if the original array is correct then the driver code will print true, else false;
Examples:
Input: arr[] = [4, 5, 3]
Output: true
Explanation: A valid original array is [3, 1, 2], pairwise sums are (3 + 1), (3 + 2) and (1 + 2).
Input: arr[] = [3]
Output: true
Explanation: One of the valid original array is [1, 2].
Constraints:
1 β€ n β€ 103
1 β€ arr[i] β€ 109
Solution:
class Solution:
def constructArr(self, arr):
if len(arr) == 1:
return [1, arr[0]-1]
s1, s2, s3 = arr[0], arr[1], arr[2]
a = (s1 + s2 - s3) // 2
res = [a]
n = 2
i = 1
while len(res) < n:
res.append(arr[i] - a)
i += 1
expected_pairs = []
for i in range(len(res)):
for j in range(i + 1, len(res)):
expected_pairs.append(res[i] + res[j])
expected_pairs.sort()
return res if expected_pairs == arr else []
Top comments (0)