Created
May 12, 2024 05:23
-
-
Save Quingsley/37f51dbff696ce22454b62b097507cb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
final result = sumZero([-6, -5, 0, 1, 2, 3, 4]); | |
print(result); | |
print(uniqueCount([-2,-1,-1, 0,1])); | |
} | |
//assume it receives a sorted array | |
// return a pair of values whose sum is 0 otherwise undefined | |
//using multiple pointers pattern | |
List<int>? sumZero(List<int> array) { | |
int left = 0; | |
int right = array.length - 1; | |
while (left < right) { | |
final sum = array[left] + array[right]; | |
if (sum == 0) { | |
return [array[left], array[right]]; | |
} else if (sum > 0) { | |
right--; | |
} else { | |
left++; | |
} | |
} | |
return null; | |
} | |
int uniqueCount(List<int> array){ | |
var count = 0; | |
if(array.isEmpty) return count; | |
count += 1; | |
var i = 0; | |
var j = i + 1; | |
while(i < array.length && j < array.length) { | |
// print(j); | |
if(array[i] != array[j]){ | |
count += 1; | |
} | |
i++; | |
j++; | |
} | |
return count; | |
} | |
// O(n) time complexity | |
// O(1) space complexity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment