forked from anuraggarg3/anuraggarg3.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Some Problems of CP
94 lines (89 loc) · 2.46 KB
/
Some Problems of CP
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//good problem of bitmasking...
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int n = nums.size();
int subsetcount = (1<<n);
vector<vector<int>> subsetsans;
for(int mask = 0;mask<subsetcount;mask++){
vector<int> subset;
for(int j=0;j<n;j++){
if((mask &(1<<j))!=0){subset.push_back(nums[j]);}
}
subsetsans.push_back(subset);
}
return subsetsans;
}
};
// A hard problem of linked list.......reverse nodes in groups of k
class Solution {
public:
ListNode* solve(ListNode* head, int k, int len){
/* Base Condition */
if(k > len || head == NULL){
return head;
}
/* reverse K nodes */
ListNode* prev = NULL;
ListNode* curr = head;
ListNode* nxt;
int c=0;
while(curr && c<k){
nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
c++;
}
head->next = solve(curr, k, len-k);
return prev;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* temp = head;
int len=0;
while(temp){
len++;
temp = temp->next;
}
return solve(head, k, len);
}
};
// A problem on binary search ....finding peak element
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int n=arr.size();
int l=0; int r=n-1; int mid;
while(l<=r){
mid=l+(r-l)/2;
if(mid>0 && mid<n-1){
if(arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1]){return mid;}
else if(arr[mid-1]>arr[mid]){r=mid-1;}
else{l=mid+1;}
}
else if(mid==0){
if(arr[0]>arr[1]){return 0;}
else{return 1;}
}
else if(arr[mid]==n-1){
if(arr[n-1]>arr[n-2]){return n-1;}
else {return n-2;}
}
}
return -1;
}
};
// program to detect cycle in linked list......fast and slow pointers
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *fast=head; ListNode *slow=head;
if(head == NULL || head->next == NULL){return false;}
while(fast->next!=NULL && fast->next->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast==slow){return true;}
}
return false;
}
};