-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
54 lines (44 loc) · 1.34 KB
/
Copy pathsolution.cpp
File metadata and controls
54 lines (44 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution
{
public:
bool isProduct(vector<int> &arr, long long target)
{
// HashSet to store visited numbers
unordered_set<long long> seen;
// Traverse every element
for (long long num : arr)
{
// Special handling for zero
if (num == 0)
{
// If target is also zero,
// then 0 multiplied with any previous number becomes 0
if (target == 0 && !seen.empty())
{
return true;
}
// Store zero and continue
seen.insert(num);
continue;
}
// If target is not divisible by current number,
// then no valid pair can exist with this number
if (target % num != 0)
{
seen.insert(num);
continue;
}
// Calculate required partner
long long needed = target / num;
// If partner already exists, pair found
if (seen.count(needed))
{
return true;
}
// Store current number for future checks
seen.insert(num);
}
// No valid pair found
return false;
}
};