Skip to content

Instantly share code, notes, and snippets.

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n=nums.size();
vector<int> lis;
for(int i=0;i<n;++i){
int lb = lower_bound(lis.begin(),lis.end(),nums[i])-lis.begin();
if(lb==lis.size())
lis.push_back(nums[i]);
else
//CPP: Dynamic Programming (Recursion + Memoization)
class Solution {
int solve(vector<int>& nums,int idx,int currOR,const int& maxOR,vector<vector<int>>& mem){
if(idx>=nums.size()) return currOR==maxOR;
if(mem[idx][currOR]!=-1) return mem[idx][currOR];
int exclude = solve(nums,idx+1,currOR,maxOR,mem);
int include = solve(nums,idx+1,currOR | nums[idx],maxOR,mem);
return mem[idx][currOR]=exclude+include;
}
//CPP: Selection Technique
class Solution {
public:
int maximumSwap(int num) {
if(num<10) return num;//No swap needed
string digits = to_string(num);
int n=digits.size();
for(int i=0;i<n-1;++i){
class Solution {
#define ll long long // Define 'll' as an alias for 'long long' to handle large numbers
public:
long long minimumSteps(string s) {
int n = s.size(); // Get the length of the input string 's'
ll total_count = 0; // Variable to store the total number of swaps needed
int leftmost_one_index = 0; // To keep track of the position of the leftmost '1'
// Find the first occurrence of '1' in the string
while(leftmost_one_index < n && s[leftmost_one_index] != '1')
class Solution {
#define ll long long
public:
long long maxKelements(vector<int>& nums, int k) {
priority_queue<ll> maxheap(nums.begin(),nums.end());//Build-Heap: O(N)
ll score=0;
while(k--){ //Run K-times only
ll curr=maxheap.top();
maxheap.pop();
//CPP: Minheap
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& nums) {
int maxVal=INT_MIN; //Max value of curent window
priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>> minheap;//{val,r,c}: Minheap
int k=nums.size();
for(int i=0;i<k;++i){ //Push 1st values of each list
maxVal=max(maxVal,nums[i][0]);
minheap.push({nums[i][0],i,0});
//SC: O(1) Optimal
class Solution {
public:
int minAddToMakeValid(string s) {
int opening=0; // Counts unmatched opening parentheses '('
int overbalanced_closing=0; // Counts unmatched closing parentheses ')'
for(int i=0; s[i]!='\0'; ++i){
if(s[i]=='(') {
opening++; // Increment for each opening '('
}
// STACK Approach: Using a stack to track imbalances
class Solution {
public:
// Function to calculate the minimum number of swaps needed to balance the string
int minSwaps(string s) {
stack<char> st; // Stack to track open brackets '['
int imbalance_count = 0; // Variable to count unbalanced closing brackets ']'
// Loop through the string
for(int i = 0; s[i] != '\0'; ++i) {