11 July 2023
Today I solved 3 Leetcode questions and continued learning dynamic programming from my course module on coding ninjas.
My approach:
This was a very easy question and I was able to solve this in O(n) time complexity.
My solution:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sumOfN = (n)*(n+1)/2;
int actualSum = 0;
for(int i=0;i<n;i++){
actualSum+=nums[i];
}
return sumOfN-actualSum;
}
};
My approach:
My very first solution was just running a for loop from 1 to n and the solution was correct but it was later when I got the error of time limit after submitting I just realized this question can easily be done using the Binary Search algorithm which would make the time complexity equals to O(logn).
My solution:
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
long int s = 1;
long int e = n;
while(s<e){
long int mid = (s+e)/2;
if(isBadVersion(mid)){
e = mid-1;
}
else{
s = mid+1;
}
}
if(isBadVersion(s)){
return s;
}else{
return s+1;
}
}
};
My approach:
The question can easily be done in O(n) time complexity but the real objective of this question was to minimize the number of operations as much as possible. The solution I wrote was correct but it was doing some extra operations which were not really necessary. It was after a while I was able to come up with the solution that takes least number of operations.
My solution:
class Solution {
public:
void swap(int* first,int* second){
int temp = *first;
*first = *second;
*second = temp;
}
void moveZeroes(vector<int>& nums) {
// optimized solution with least number of operations
if(nums.size()==1){
return;
}
int prev = 0;
int next = 0;
while(next<nums.size()){
if(nums[next]!=0){
swap(&nums[prev],&nums[next]);
prev++;
}
next++;
}
/// This solution was taking extra time to implement .
// int countZero = 0;
// int i = 1;
// while(i<nums.size()){
// if(nums[i-1]==0 && nums[i]!=0){
// swap(&nums[i-countZero-1],&nums[i]);
// if(i==nums.size()-1){
// return;
// }
// i = i-countZero+1;
// countZero = 0;
// }
// else if(nums[i-1]==0 && nums[i]==0){
// countZero++;
// i++;
// }
// else{
// i++;
// }
// }
}
};
Apart from this I was learning Dynamic Programming. It's kinda complicated but I am having fun learning.