Current streak:
0 days
Longest streak:
10 days
Less
More
#include <bits/stdc++.h>
vector<vector<int>> pairSum(vector<int> &arr, int s){
sort(arr.begin(), arr.end());
vector<vector<int>>ans;
for(int i=0;i<arr.size()-1;i++){
vector<int>temp;
for(int j=i+1;j<arr.size();j++){
if(arr[i]+arr[j]==s){
temp.push_back(arr[i]);
temp.push_back(arr[j]);
ans.push_back(temp);
}
if(arr[i]+arr[j]>s){
break;
}
}
}
return ans;
}
BinaryTreeNode<int>* lcaOfTwoNodes(BinaryTreeNode<int>* root, int node1, int node2) {
if (root == NULL) {
return NULL;
}
if (root->data == node1 || root->data == node2) {
return root;
}
BinaryTreeNode<int>* leftLCA = lcaOfTwoNodes(root->left, node1, node2);
BinaryTreeNode<int>* rightLCA = lcaOfTwoNodes(root->right, node1, node2);
if (leftLCA != NULL && rightLCA != NULL) {
return root;
}
if (leftLCA != NULL) {
return leftLCA;
}
return rightLCA;
}
BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {
if (root == NULL) {
return NULL;
}
BinaryTreeNode<int>* lca12 = lcaOfTwoNodes(root, node1, node2);
BinaryTreeNode<int>* lca = lcaOfTwoNodes(root, lca12->data, node3);
return lca;
}
We are basically taking a variable with initial value 0 and then performing XOR Operation. When a same number is XORed, it results in 0, otherwise the number is retained as per truth table of XOR.
Since all other elements appear twice, they cancel out and at the end, only the variable appearing once retains.
int findUnique(int *arr, int size){
int ans = 0;
for ( int i = 0 ; i < size ; i++ )
ans = ans ^ arr[i];
return ans;
}
#include <iostream>
#include <string>
using namespace std;
bool isSpecialNumber(int num) {
string binary = bitset<32>(num).to_string();
size_t pos = binary.find("101");
return (pos != string::npos);
}
int kthSpecialNumber(int l, int r, int k) {
int count = 0; for (int num = l; num <= r; num++) {
if (isSpecialNumber(num)) {
count++;
if (count == k) return num;
}
}
return -1;
}