21BCS8358 - Smiksha (IT Day3)
21BCS8358 - Smiksha (IT Day3)
21BCS8358 - Smiksha (IT Day3)
Worksheet Day 4
Aim:
To demonstrate the concept of programming algorithms.
Objective:
2) Reverse Integer- Given a signed 32-bit integer x, return x with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. (Level –
Medium)
3) Permutations - Given an array nums of distinct integers, return all the possible permutations. You can
return the answer in any order.. (Level – Medium)
4) Find Minimum in Rotated Sorted Array II . - Suppose an array of length n sorted in ascending order is
rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:. (Level –
Hard)
Code:
1) class Solution {
public:
Naman 21BCS8137
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
while(head != NULL){
leftTail->next = head;
leftTail = leftTail->next;
else{
rightTail->next = head;
rightTail = rightTail->next;
head = head->next;
leftTail->next = right->next;
rightTail->next = NULL;
return left->next;
};
2)
class Solution {
public:
int reverse(int x) {
long r=0;
while(x){
r=r*10+x%10;
Naman 21BCS8137
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
x=x/10;
}
3) class Solution {
public:
vector<vector<int>> result;
// Backtracking
void permutation(vector<int> &nums,int i,int n){
if(i==n){
result.push_back(nums);
return ;
}
for(int j=i;j<=n;j++){
swap( nums[i],nums[j]);
permutation(nums,i+1,n);
swap( nums[i],nums[j]);
}
}
permutation(nums,0,nums.size()-1);
return result;
}
};
4) class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r && nums[l] > nums[r]) {
int m = l + (r - l) / 2;
if (nums[m] > nums[m + 1]) {
return nums[m + 1];
}
Naman 21BCS8137
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if (nums[m] > nums[r]) {
l = m + 1;
} else {
r = m;
}
}
return findMin(nums, l, r);
}
private:
int findMin(vector<int>& nums, int l, int r) {
int mini = nums[l++];
while (l <= r) {
mini = min(mini, nums[l++]);
}
return mini;
}
Output:
1)
Naman 21BCS8137
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
2)
3)
Naman 21BCS8137
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
4)
Naman 21BCS8137