Code
stringlengths 55
5.79k
| Input size
stringlengths 9
46
| Time Complexity
stringlengths 4
17
| Unnamed: 3
float64 | text
stringlengths 168
5.9k
|
---|---|---|---|---|
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int first,last;
first=0;
last=1000000-1;
int answer=last;
while(first<last){
int middle=(first+last)/2;
if(possible(heights,middle)){
answer=min(answer,middle);
last=middle;
}
else{
first=middle+1;
}
}
return answer;
}
bool possible(vector<vector<int>>& heights,int search){
priority_queue<vector<int>, vector<vector<int>>, function<bool(vector<int>&, vector<int>&)>>
pq([&](vector<int>& a, vector<int>& b) { return a[0] > b[0]; });
int m=heights.size();
int n=heights[0].size();
vector<vector<int>> directions={{0,1},{1,0},{0,-1},{-1,0}};
pq.push({0,0,0});
vector<vector<bool>> visited(m, vector<bool>(n, false));
visited[0][0] = true;
while(!pq.empty()){
auto metric=pq.top();
pq.pop();
if(metric[1]==m-1 && metric[2]==n-1){
return true;
}
for(auto& x:directions){
int nx,ny;
nx=metric[1]+x[0];
ny=metric[2]+x[1];
if(nx>=0 && nx<=m-1 && ny>=0 && ny<=n-1 && !visited[nx][ny]){
int new_cost=abs(heights[nx][ny]-heights[metric[1]][metric[2]]);
if(new_cost<=search){
pq.push({max(new_cost,metric[0]),nx,ny});
visited[nx][ny]=true;
}
}
}
}
return false;
}
}; | m x n matrix | O(m*n*log(mn)) | null | <s>[INST]class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int first,last;
first=0;
last=1000000-1;
int answer=last;
while(first<last){
int middle=(first+last)/2;
if(possible(heights,middle)){
answer=min(answer,middle);
last=middle;
}
else{
first=middle+1;
}
}
return answer;
}
bool possible(vector<vector<int>>& heights,int search){
priority_queue<vector<int>, vector<vector<int>>, function<bool(vector<int>&, vector<int>&)>>
pq([&](vector<int>& a, vector<int>& b) { return a[0] > b[0]; });
int m=heights.size();
int n=heights[0].size();
vector<vector<int>> directions={{0,1},{1,0},{0,-1},{-1,0}};
pq.push({0,0,0});
vector<vector<bool>> visited(m, vector<bool>(n, false));
visited[0][0] = true;
while(!pq.empty()){
auto metric=pq.top();
pq.pop();
if(metric[1]==m-1 && metric[2]==n-1){
return true;
}
for(auto& x:directions){
int nx,ny;
nx=metric[1]+x[0];
ny=metric[2]+x[1];
if(nx>=0 && nx<=m-1 && ny>=0 && ny<=n-1 && !visited[nx][ny]){
int new_cost=abs(heights[nx][ny]-heights[metric[1]][metric[2]]);
if(new_cost<=search){
pq.push({max(new_cost,metric[0]),nx,ny});
visited[nx][ny]=true;
}
}
}
}
return false;
}
};# input: m x n matrix [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
import heapq
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
pq=[(0,0,0)]
visited=set()
m=len(grid)
n=len(grid[0])
cost_matrix = [[float('inf')] * n for _ in range(m)]
cost_matrix[0][0]=0
directions=[(1,0),(0,1),(-1,0),(0,-1)]
while(pq):
cost,x,y=heapq.heappop(pq)
if (x,y) in visited:
continue
visited.add((x,y))
if x==m-1 and y==n-1:
return cost
for dx,dy in directions:
if(0<=x+dx<=m-1 and 0<=y+dy<=n-1):
new_cost=cost+grid[x+dx][y+dy]
if(new_cost<cost_matrix[x+dx][y+dy]):
heapq.heappush(pq,(cost+grid[x+dx][y+dy],x+dx,y+dy))
cost_matrix[x+dx][y+dy]=new_cost
return -1
| m x n matrix | O(mnlog(mn)) | null | <s>[INST]
import heapq
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
pq=[(0,0,0)]
visited=set()
m=len(grid)
n=len(grid[0])
cost_matrix = [[float('inf')] * n for _ in range(m)]
cost_matrix[0][0]=0
directions=[(1,0),(0,1),(-1,0),(0,-1)]
while(pq):
cost,x,y=heapq.heappop(pq)
if (x,y) in visited:
continue
visited.add((x,y))
if x==m-1 and y==n-1:
return cost
for dx,dy in directions:
if(0<=x+dx<=m-1 and 0<=y+dy<=n-1):
new_cost=cost+grid[x+dx][y+dy]
if(new_cost<cost_matrix[x+dx][y+dy]):
heapq.heappush(pq,(cost+grid[x+dx][y+dy],x+dx,y+dy))
cost_matrix[x+dx][y+dy]=new_cost
return -1
# input: m x n matrix [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class MergeSort {
public:
void sort(vector<int>& array) {
if (array.empty()) return;
mergeSort(array, 0, array.size() - 1);
}
private:
void mergeSort(vector<int>& array, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
void merge(vector<int>& array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> leftArray(n1);
vector<int> rightArray(n2);
for (int i = 0; i < n1; i++)
leftArray[i] = array[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = array[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
}; | array of n | O(nlogn)
| null | <s>[INST]class MergeSort {
public:
void sort(vector<int>& array) {
if (array.empty()) return;
mergeSort(array, 0, array.size() - 1);
}
private:
void mergeSort(vector<int>& array, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
void merge(vector<int>& array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> leftArray(n1);
vector<int> rightArray(n2);
for (int i = 0; i < n1; i++)
leftArray[i] = array[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = array[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
};# input: array of n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
} | array of n | O(n log n) | null | <s>[INST]void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}# input: array of n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
} | array of n | O(n) | null | <s>[INST]void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}# input: array of n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int n=str1.size();
int m=str2.size();
vector<vector<int>> dp(m+1,vector<int> (n+1,0));
for(int i=m-1;i>=0;i--){
for(int j=n-1;j>=0;j--){
if(str1[j]==str2[i]){
dp[i][j]=1+dp[i+1][j+1];
}
else{
dp[i][j]=max(dp[i+1][j],dp[i][j+1]);
}
}
}
string answer="";
int i=0;
int j=0;
while(i<m && j<n){
if(str1[j]==str2[i]){
answer+=str2[i];
i++;
j++;
}
else if(dp[i+1][j]>dp[i][j+1]){
answer+=str2[i];
i++;
}
else{
answer+=str1[j];
j++;
}
}
while(j<n){
answer+=str1[j];
j++;
}
while(i<m){
answer+=str2[i];
i++;
}
// reverse(answer.begin(),answer.end());
return answer;
}
}; | two strings of size m and n | O(mn) | null | <s>[INST]class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int n=str1.size();
int m=str2.size();
vector<vector<int>> dp(m+1,vector<int> (n+1,0));
for(int i=m-1;i>=0;i--){
for(int j=n-1;j>=0;j--){
if(str1[j]==str2[i]){
dp[i][j]=1+dp[i+1][j+1];
}
else{
dp[i][j]=max(dp[i+1][j],dp[i][j+1]);
}
}
}
string answer="";
int i=0;
int j=0;
while(i<m && j<n){
if(str1[j]==str2[i]){
answer+=str2[i];
i++;
j++;
}
else if(dp[i+1][j]>dp[i][j+1]){
answer+=str2[i];
i++;
}
else{
answer+=str1[j];
j++;
}
}
while(j<n){
answer+=str1[j];
j++;
}
while(i<m){
answer+=str2[i];
i++;
}
// reverse(answer.begin(),answer.end());
return answer;
}
};# input: two strings of size m and n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ips;
if(s.size()>12){
return ips;
}
string curr="";
backtrack(ips,s,0,0,curr);
for(auto x:ips){
cout<<x<<endl;
}
return ips;
}
void backtrack(vector<string>& ips,string& s,int i,int dots,string curr){
if(dots==4 && i==s.size() ){
int len=curr.size();
ips.push_back(curr.substr(0,len-1));
return;
}
if(dots>4){
return;
}
for(int j=i;j<mini(i+3,(int)s.size());j++){
string seg=s.substr(i,j-i+1);
int number=stoi(seg);
if(number<=255 && (i==j || s[i]!='0')){
backtrack(ips,s,j+1,dots+1,curr+seg+'.');
}
}
}
int mini(int x,int y){
return x>y?y:x;
}
}; | string of size n | O(3^n) | null | <s>[INST]class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ips;
if(s.size()>12){
return ips;
}
string curr="";
backtrack(ips,s,0,0,curr);
for(auto x:ips){
cout<<x<<endl;
}
return ips;
}
void backtrack(vector<string>& ips,string& s,int i,int dots,string curr){
if(dots==4 && i==s.size() ){
int len=curr.size();
ips.push_back(curr.substr(0,len-1));
return;
}
if(dots>4){
return;
}
for(int j=i;j<mini(i+3,(int)s.size());j++){
string seg=s.substr(i,j-i+1);
int number=stoi(seg);
if(number<=255 && (i==j || s[i]!='0')){
backtrack(ips,s,j+1,dots+1,curr+seg+'.');
}
}
}
int mini(int x,int y){
return x>y?y:x;
}
};# input: string of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class InsertionSort {
private:
int* arr;
int size;
public:
InsertionSort(int arr[], int n) {
size = n;
this->arr = new int[size];
for (int i = 0; i < size; i++) {
this->arr[i] = arr[i];
}
}
void sort() {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
~InsertionSort() {
delete[] arr;
}
}; | array of n | O(n) | null | <s>[INST]class InsertionSort {
private:
int* arr;
int size;
public:
InsertionSort(int arr[], int n) {
size = n;
this->arr = new int[size];
for (int i = 0; i < size; i++) {
this->arr[i] = arr[i];
}
}
void sort() {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
~InsertionSort() {
delete[] arr;
}
};# input: array of n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include<stdio.h>
#include<stdlib.h>
int matrix[10][10];
int min(int n,int m){
if(n>m){
return m;
}
return n;
}
void folyd(int n){
int i,j,k;
for(k=0;k<n;k++){
for(i=0;i<n;i++){
for(j=0;j<n;j++){
matrix[i][j]=min(matrix[i][j],matrix[i][k]+matrix[k][j]);
}
}
}
printf("all pair shortest path:\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
int main(){
int n;
printf("enter n:");
scanf("%d",&n);
printf("enter matrix:");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&matrix[i][j]);
}
}
folyd(n);
return 0;
}
| matrix of size n x n | O(n^3) | null | <s>[INST]#include<stdio.h>
#include<stdlib.h>
int matrix[10][10];
int min(int n,int m){
if(n>m){
return m;
}
return n;
}
void folyd(int n){
int i,j,k;
for(k=0;k<n;k++){
for(i=0;i<n;i++){
for(j=0;j<n;j++){
matrix[i][j]=min(matrix[i][j],matrix[i][k]+matrix[k][j]);
}
}
}
printf("all pair shortest path:\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
int main(){
int n;
printf("enter n:");
scanf("%d",&n);
printf("enter matrix:");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&matrix[i][j]);
}
}
folyd(n);
return 0;
}
# input: matrix of size n x n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 256
int table[256];
void table_init(char P[],int m){
for(int i=0;i<MAX;i++){
table[i]=m;
}
for(int j=0;j<m-1;j++){
table[(int)P[j]]=m-1-j;
}
}
int horspool(char P[],char T[],int m,int n){
int k;
int i=m;
while(i<n){
k=0;
while(k<m && P[m-1-k]==T[i-k]){
k++;
}
if(k==m){
return i-m+1;
}
else{
i+=table[(int)T[i]];
}
}
return -1;
}
int main(){
char P[20],T[MAX];
printf("enter text:");
scanf("%s",T);
printf("enter pattern:");
scanf("%s",P);
int m,n;
m=strlen(P);
n=strlen(T);
table_init(P,m);
int answer=horspool(P,T,m,n);
answer!=-1?printf("index=%d\n",answer):printf("not found\n");
return 0;
} | string of size n | O(n) | null | <s>[INST]#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 256
int table[256];
void table_init(char P[],int m){
for(int i=0;i<MAX;i++){
table[i]=m;
}
for(int j=0;j<m-1;j++){
table[(int)P[j]]=m-1-j;
}
}
int horspool(char P[],char T[],int m,int n){
int k;
int i=m;
while(i<n){
k=0;
while(k<m && P[m-1-k]==T[i-k]){
k++;
}
if(k==m){
return i-m+1;
}
else{
i+=table[(int)T[i]];
}
}
return -1;
}
int main(){
char P[20],T[MAX];
printf("enter text:");
scanf("%s",T);
printf("enter pattern:");
scanf("%s",P);
int m,n;
m=strlen(P);
n=strlen(T);
table_init(P,m);
int answer=horspool(P,T,m,n);
answer!=-1?printf("index=%d\n",answer):printf("not found\n");
return 0;
}# input: string of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int main(){
int n=4;
int profit[4]={8,6,16,11};
int weight[4]={2,1,3,2};
int W=5;
int table[5][6];
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
if(i==0||j==0){
table[i][j]=0;
}
else if(j-weight[i-1]<0){
table[i][j]=table[i-1][j];
}
else{
table[i][j]=max(table[i-1][j],profit[i-1]+table[i-1][j-weight[i-1]]);
}
}
}
printf("max profit:\n");
printf("%d\n",table[n][W]);
return 0;
}
| two arrays of size n | O(n^2) | null | <s>[INST]int main(){
int n=4;
int profit[4]={8,6,16,11};
int weight[4]={2,1,3,2};
int W=5;
int table[5][6];
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
if(i==0||j==0){
table[i][j]=0;
}
else if(j-weight[i-1]<0){
table[i][j]=table[i-1][j];
}
else{
table[i][j]=max(table[i-1][j],profit[i-1]+table[i-1][j-weight[i-1]]);
}
}
}
printf("max profit:\n");
printf("%d\n",table[n][W]);
return 0;
}
# input: two arrays of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void countingSort(int arr[], int n) {
int maxElem = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElem) {
maxElem = arr[i];
}
}
vector<int> count(maxElem + 1, 0);
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
int index = 0;
for (int i = 0; i <= maxElem; i++) {
while (count[i] > 0) {
arr[index] = i;
index++;
count[i]--;
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
| array of n | O(n+k) | null | <s>[INST]void countingSort(int arr[], int n) {
int maxElem = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElem) {
maxElem = arr[i];
}
}
vector<int> count(maxElem + 1, 0);
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
int index = 0;
for (int i = 0; i <= maxElem; i++) {
while (count[i] > 0) {
arr[index] = i;
index++;
count[i]--;
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
# input: array of n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
bool canJump(vector<int>& nums) {
int left,right;
left=right=0;
int furthest;
while(right<nums.size()-1){
furthest=0;
for(int i=left;i<right+1;i++){
furthest=max(furthest,i+nums[i]);
}
left=right+1;
right=furthest;
if(left>right){
return false;
}
}
return true;
}
}; | array of size n | O(n) | null | <s>[INST]class Solution {
public:
bool canJump(vector<int>& nums) {
int left,right;
left=right=0;
int furthest;
while(right<nums.size()-1){
furthest=0;
for(int i=left;i<right+1;i++){
furthest=max(furthest,i+nums[i]);
}
left=right+1;
right=furthest;
if(left>right){
return false;
}
}
return true;
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for i in s:
if i=='(' or i=='[' or i=='{':
stack.append(i)
else:
if (i=='}' or i==')' or i==']') and len(stack)==0:
return False
else:
if(i==')' or i=='}' or i==']'):
popper=stack.pop()
if(popper=='(' and i!=')'):
return False
elif(popper=='[' and i!=']'):
return False
elif(popper=='{' and i!='}'):
return False
if(len(stack)>0):
return False
return True
| string of size n | O(n) | null | <s>[INST]class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for i in s:
if i=='(' or i=='[' or i=='{':
stack.append(i)
else:
if (i=='}' or i==')' or i==']') and len(stack)==0:
return False
else:
if(i==')' or i=='}' or i==']'):
popper=stack.pop()
if(popper=='(' and i!=')'):
return False
elif(popper=='[' and i!=']'):
return False
elif(popper=='{' and i!='}'):
return False
if(len(stack)>0):
return False
return True
# input: string of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class RadixSort {
private:
int getMax(int arr[], int n) {
int maxElem = arr[0];
for (int i = 1; i < n; i++) {
maxElem = max(maxElem, arr[i]);
}
return maxElem;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
int count[10] = {0};
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
public:
void radixSort(int arr[], int n) {
int maxElem = getMax(arr, n);
for (int exp = 1; maxElem / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
}; | array of size n | O(m*n) | null | <s>[INST]class RadixSort {
private:
int getMax(int arr[], int n) {
int maxElem = arr[0];
for (int i = 1; i < n; i++) {
maxElem = max(maxElem, arr[i]);
}
return maxElem;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
int count[10] = {0};
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
public:
void radixSort(int arr[], int n) {
int maxElem = getMax(arr, n);
for (int exp = 1; maxElem / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row,col=len(matrix),len(matrix[0])
start,end=0,(row*col)-1
while start<=end:
middle=(start+end)//2
mid_value=matrix[middle//col][middle%col]
if mid_value==target:
return True
elif mid_value>target:
end=middle-1
else:
start=middle+1
return False
| matrix of size m x n | O(log(m*n)) | null | <s>[INST]class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row,col=len(matrix),len(matrix[0])
start,end=0,(row*col)-1
while start<=end:
middle=(start+end)//2
mid_value=matrix[middle//col][middle%col]
if mid_value==target:
return True
elif mid_value>target:
end=middle-1
else:
start=middle+1
return False
# input: matrix of size m x n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def mySqrt(self, x: int) -> int:
left=0
right=x
while left<=right:
middle=(left+right)//2
if middle*middle<x:
left=middle+1
elif middle*middle>x:
right=middle-1
else:
return middle
return right
| integer n | O(log(n)) | null | <s>[INST]class Solution:
def mySqrt(self, x: int) -> int:
left=0
right=x
while left<=right:
middle=(left+right)//2
if middle*middle<x:
left=middle+1
elif middle*middle>x:
right=middle-1
else:
return middle
return right
# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL){
return true;
}
else if(p==NULL || q==NULL){
return false;
}
return q->val==p->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
}; | two binary trees of n nodes | O(n) | null | <s>[INST]class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL){
return true;
}
else if(p==NULL || q==NULL){
return false;
}
return q->val==p->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};# input: two binary trees of n nodes [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root==None:
return False
if root.left==None and root.right==None:
return targetSum==root.val
leftsum=self.hasPathSum(root.left,targetSum-root.val)
rightsum=self.hasPathSum(root.right,targetSum-root.val)
return leftsum or rightsum
| binary tree with n nodes | O(n) | null | <s>[INST]class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root==None:
return False
if root.left==None and root.right==None:
return targetSum==root.val
leftsum=self.hasPathSum(root.left,targetSum-root.val)
rightsum=self.hasPathSum(root.right,targetSum-root.val)
return leftsum or rightsum
# input: binary tree with n nodes [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void bucketSort(float arr[], int n) {
vector<float> buckets[n];
float maxElem = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElem) {
maxElem = arr[i];
}
}
for (int i = 0; i < n; i++) {
int index = arr[i] * n;
buckets[index].push_back(arr[i]);
}
for (int i = 0; i < n; i++) {
sort(buckets[i].begin(), buckets[i].end());
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i][j];
}
}
}
void printArray(float arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
} | array of size n | O(nlogn)
| null | <s>[INST]void bucketSort(float arr[], int n) {
vector<float> buckets[n];
float maxElem = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElem) {
maxElem = arr[i];
}
}
for (int i = 0; i < n; i++) {
int index = arr[i] * n;
buckets[index].push_back(arr[i]);
}
for (int i = 0; i < n; i++) {
sort(buckets[i].begin(), buckets[i].end());
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
arr[index++] = buckets[i][j];
}
}
}
void printArray(float arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
answer=[[1]]
n=numRows
if numRows==1:
return answer
count=2
for i in range(2,n+1):
temp=[]
for j in range(0,count):
if j ==0 or j==count-1:
temp.append(answer[-1][0])
else:
temp.append(answer[-1][j]+answer[-1][j-1])
count+=1
answer.append(temp)
return answer
| integer n | O(n^2) | null | <s>[INST]class Solution:
def generate(self, numRows: int) -> List[List[int]]:
answer=[[1]]
n=numRows
if numRows==1:
return answer
count=2
for i in range(2,n+1):
temp=[]
for j in range(0,count):
if j ==0 or j==count-1:
temp.append(answer[-1][0])
else:
temp.append(answer[-1][j]+answer[-1][j-1])
count+=1
answer.append(temp)
return answer
# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
unordered_map<int,vector<int>> premap;
set<int> visited;
for(int i=0;i<numCourses;i++){
premap[i]={};
}
for(auto x: prerequisites){
premap[x[0]].push_back(x[1]);
}
for(int i=0;i<numCourses;i++){
if(!dfs(i,visited,premap)){
return false;
}
}
return true;
}
bool dfs(int crs,set<int>& visited,unordered_map<int,vector<int>>& premap){
if(visited.find(crs)!=visited.end()){
return false;
}
if(premap[crs].empty()){
return true;
}
visited.insert(crs);
for(auto pre:premap[crs]){
if(!dfs(pre,visited,premap)){
return false;
}
}
visited.erase(crs);
premap[crs]={};
return true;
}
};
| arrays of size V and E | O(V+E) | null | <s>[INST]class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
unordered_map<int,vector<int>> premap;
set<int> visited;
for(int i=0;i<numCourses;i++){
premap[i]={};
}
for(auto x: prerequisites){
premap[x[0]].push_back(x[1]);
}
for(int i=0;i<numCourses;i++){
if(!dfs(i,visited,premap)){
return false;
}
}
return true;
}
bool dfs(int crs,set<int>& visited,unordered_map<int,vector<int>>& premap){
if(visited.find(crs)!=visited.end()){
return false;
}
if(premap[crs].empty()){
return true;
}
visited.insert(crs);
for(auto pre:premap[crs]){
if(!dfs(pre,visited,premap)){
return false;
}
}
visited.erase(crs);
premap[crs]={};
return true;
}
};
# input: arrays of size V and E [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
vector<bool> prime(n + 1, true);
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not c
hanged, then it is a prime
if (prime[p] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which are
// multiple of p and are less than p^2 are
// already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p = 2; p <= n; p++)
if (prime[p])
cout << p << " ";
}
// Driver Code
int main()
{
int n = 30;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
} | integer n | O(N*log(log(N))) | null | <s>[INST]#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
vector<bool> prime(n + 1, true);
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not c
hanged, then it is a prime
if (prime[p] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which are
// multiple of p and are less than p^2 are
// already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p = 2; p <= n; p++)
if (prime[p])
cout << p << " ";
}
// Driver Code
int main()
{
int n = 30;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class HeapSort {
public:
void sort(vector<int>& arr) {
int n = arr.size();
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void printArray(const vector<int>& arr) {
for (int i : arr)
cout << i << " ";
cout << endl;
}
private:
void heapify(vector<int>& arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
}; | array of size n | O(nlogn) | null | <s>[INST]class HeapSort {
public:
void sort(vector<int>& arr) {
int n = arr.size();
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void printArray(const vector<int>& arr) {
for (int i : arr)
cout << i << " ";
cout << endl;
}
private:
void heapify(vector<int>& arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <vector>
using namespace std;
int linearSearch(const vector<int>& arr, int target) {
for (int i = 0; i < arr.size(); ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
vector<int> arr = {10, 23, 45, 70, 11, 15};
int target = 70;
cout << "Array: ";
for (int i : arr) {
cout << i << " ";
}
cout << endl;
int result = linearSearch(arr, target);
if (result != -1) {
cout << "Element " << target << " found at index " << result << "." << endl;
} else {
cout << "Element " << target << " not found in the array." << endl;
}
return 0;
} | array of size n | O(n) | null | <s>[INST]#include <iostream>
#include <vector>
using namespace std;
int linearSearch(const vector<int>& arr, int target) {
for (int i = 0; i < arr.size(); ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
vector<int> arr = {10, 23, 45, 70, 11, 15};
int target = 70;
cout << "Array: ";
for (int i : arr) {
cout << i << " ";
}
cout << endl;
int result = linearSearch(arr, target);
if (result != -1) {
cout << "Element " << target << " found at index " << result << "." << endl;
} else {
cout << "Element " << target << " not found in the array." << endl;
}
return 0;
}# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class BinarySearch {
public:
int search(const vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
void printArray(const vector<int>& arr) {
for (int i : arr) {
cout << i << " ";
}
cout << endl;
}
}; | array of size n | O(logn) | null | <s>[INST]class BinarySearch {
public:
int search(const vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
void printArray(const vector<int>& arr) {
for (int i : arr) {
cout << i << " ";
}
cout << endl;
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int interpolationSearch(const vector<int>& arr, int target) {
int low = 0;
int high = arr.size() - 1;
while (low <= high && target >= arr[low] && target <= arr[high]) {
if (low == high) {
if (arr[low] == target) {
return low;
}
return -1;
}
int pos = low + ((double)(high - low) / (arr[high] - arr[low]) * (target - arr[low]));
if (arr[pos] == target) {
return pos;
}
if (arr[pos] < target) {
low = pos + 1;
}
else {
high = pos - 1;
}
}
return -1;
} | array of size n | O(loglogn) | null | <s>[INST]int interpolationSearch(const vector<int>& arr, int target) {
int low = 0;
int high = arr.size() - 1;
while (low <= high && target >= arr[low] && target <= arr[high]) {
if (low == high) {
if (arr[low] == target) {
return low;
}
return -1;
}
int pos = low + ((double)(high - low) / (arr[high] - arr[low]) * (target - arr[low]));
if (arr[pos] == target) {
return pos;
}
if (arr[pos] < target) {
low = pos + 1;
}
else {
high = pos - 1;
}
}
return -1;
}# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class JumpSearch {
public:
int search(const vector<int>& arr, int target) {
int n = arr.size();
int step = sqrt(n);
int prev = 0;
while (arr[min(step, n) - 1] < target) {
prev = step;
step += sqrt(n);
if (prev >= n) {
return -1;
}
}
for (int i = prev; i < min(step, n); ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
void printArray(const vector<int>& arr) {
for (int i : arr) {
cout << i << " ";
}
cout << endl;
}
}; | array of size n | O(n^-1) | null | <s>[INST]class JumpSearch {
public:
int search(const vector<int>& arr, int target) {
int n = arr.size();
int step = sqrt(n);
int prev = 0;
while (arr[min(step, n) - 1] < target) {
prev = step;
step += sqrt(n);
if (prev >= n) {
return -1;
}
}
for (int i = prev; i < min(step, n); ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
void printArray(const vector<int>& arr) {
for (int i : arr) {
cout << i << " ";
}
cout << endl;
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class HashTable {
private:
int numBuckets;
vector<list<int>> table;
public:
HashTable(int size) {
numBuckets = size;
table.resize(numBuckets);
}
int hashFunction(int key) {
return key % numBuckets;
}
void insert(int key) {
int index = hashFunction(key);
table[index].push_back(key);
}
bool search(int key) {
int index = hashFunction(key);
for (int item : table[index]) {
if (item == key) {
return true;
}
}
return false;
}
void display() {
for (int i = 0; i < numBuckets; i++) {
cout << "Bucket " << i << ": ";
for (int item : table[i]) {
cout << item << " -> ";
}
cout << "NULL" << endl;
}
}
};
int main() {
int arr[] = {10, 20, 30, 15, 25};
int n = sizeof(arr) / sizeof(arr[0]);
HashTable hashTable(7);
for (int i = 0; i < n; i++) {
hashTable.insert(arr[i]);
}
hashTable.display();
int keyToSearch = 15;
if (hashTable.search(keyToSearch)) {
cout << "Element " << keyToSearch << " found in the hash table." << endl;
} else {
cout << "Element " << keyToSearch << " not found in the hash table." << endl;
}
keyToSearch = 100;
if (hashTable.search(keyToSearch)) {
cout << "Element " << keyToSearch << " found in the hash table." << endl;
} else {
cout << "Element " << keyToSearch << " not found in the hash table." << endl;
}
return 0;
}
| array of size n | O(n) | null | <s>[INST]#include <iostream>
#include <vector>
#include <list>
using namespace std;
class HashTable {
private:
int numBuckets;
vector<list<int>> table;
public:
HashTable(int size) {
numBuckets = size;
table.resize(numBuckets);
}
int hashFunction(int key) {
return key % numBuckets;
}
void insert(int key) {
int index = hashFunction(key);
table[index].push_back(key);
}
bool search(int key) {
int index = hashFunction(key);
for (int item : table[index]) {
if (item == key) {
return true;
}
}
return false;
}
void display() {
for (int i = 0; i < numBuckets; i++) {
cout << "Bucket " << i << ": ";
for (int item : table[i]) {
cout << item << " -> ";
}
cout << "NULL" << endl;
}
}
};
int main() {
int arr[] = {10, 20, 30, 15, 25};
int n = sizeof(arr) / sizeof(arr[0]);
HashTable hashTable(7);
for (int i = 0; i < n; i++) {
hashTable.insert(arr[i]);
}
hashTable.display();
int keyToSearch = 15;
if (hashTable.search(keyToSearch)) {
cout << "Element " << keyToSearch << " found in the hash table." << endl;
} else {
cout << "Element " << keyToSearch << " not found in the hash table." << endl;
}
keyToSearch = 100;
if (hashTable.search(keyToSearch)) {
cout << "Element " << keyToSearch << " found in the hash table." << endl;
} else {
cout << "Element " << keyToSearch << " not found in the hash table." << endl;
}
return 0;
}
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <string>
using namespace std;
int naiveStringMatch(const string& T, const string& P) {
int n = T.length();
int m = P.length();
for (int i = 0; i <= n - m; i++) {
int j = 0;
while (j < m && T[i + j] == P[j]) {
j++;
}
if (j == m) {
return i;
}
}
return -1;
}
int main() {
string text = "abcabcabc";
string pattern = "abc";
int result = naiveStringMatch(text, pattern);
if (result != -1) {
cout << "Pattern found at index " << result << endl;
} else {
cout << "Pattern not found" << endl;
}
return 0;
}
| Two string of size m and n | O(m*n) | null | <s>[INST]#include <iostream>
#include <string>
using namespace std;
int naiveStringMatch(const string& T, const string& P) {
int n = T.length();
int m = P.length();
for (int i = 0; i <= n - m; i++) {
int j = 0;
while (j < m && T[i + j] == P[j]) {
j++;
}
if (j == m) {
return i;
}
}
return -1;
}
int main() {
string text = "abcabcabc";
string pattern = "abc";
int result = naiveStringMatch(text, pattern);
if (result != -1) {
cout << "Pattern found at index " << result << endl;
} else {
cout << "Pattern not found" << endl;
}
return 0;
}
# input: Two string of size m and n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Graph {
private:
int numVertices;
vector<vector<int>> adjMatrix;
public:
Graph(int vertices) {
numVertices = vertices;
adjMatrix.resize(numVertices, vector<int>(numVertices, 0));
}
void addEdge(int src, int dest) {
adjMatrix[src][dest] = 1;
adjMatrix[dest][src] = 1;
}
void DFS(int startVertex) {
vector<bool> visited(numVertices, false);
DFSUtil(startVertex, visited);
}
private:
void DFSUtil(int vertex, vector<bool>& visited) {
visited[vertex] = true;
cout << "Visited " << vertex << " ";
for (int i = 0; i < numVertices; i++) {
if (adjMatrix[vertex][i] == 1 && !visited[i]) {
DFSUtil(i, visited);
}
}
}
};
| Two array of size Eand V | O(V+E) | null | <s>[INST]class Graph {
private:
int numVertices;
vector<vector<int>> adjMatrix;
public:
Graph(int vertices) {
numVertices = vertices;
adjMatrix.resize(numVertices, vector<int>(numVertices, 0));
}
void addEdge(int src, int dest) {
adjMatrix[src][dest] = 1;
adjMatrix[dest][src] = 1;
}
void DFS(int startVertex) {
vector<bool> visited(numVertices, false);
DFSUtil(startVertex, visited);
}
private:
void DFSUtil(int vertex, vector<bool>& visited) {
visited[vertex] = true;
cout << "Visited " << vertex << " ";
for (int i = 0; i < numVertices; i++) {
if (adjMatrix[vertex][i] == 1 && !visited[i]) {
DFSUtil(i, visited);
}
}
}
};
# input: Two array of size Eand V [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(const string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string inputs[] = {
"A man, a plan, a canal, Panama",
"racecar",
"hello",
"Was it a car or a cat I saw",
"No 'x' in Nixon"
};
for (const auto& input : inputs) {
cout << "Input: " << input << endl;
string cleanedInput;
for (char c : input) {
if (isalnum(c)) {
cleanedInput += tolower(c);
}
}
if (isPalindrome(cleanedInput)) {
cout << "Output: The string is a palindrome." << endl;
} else {
cout << "Output: The string is not a palindrome." << endl;
}
cout << "-----------------------------------" << endl;
}
return 0;
}
| string of size n | O(n) | null | <s>[INST]#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(const string& str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string inputs[] = {
"A man, a plan, a canal, Panama",
"racecar",
"hello",
"Was it a car or a cat I saw",
"No 'x' in Nixon"
};
for (const auto& input : inputs) {
cout << "Input: " << input << endl;
string cleanedInput;
for (char c : input) {
if (isalnum(c)) {
cleanedInput += tolower(c);
}
}
if (isPalindrome(cleanedInput)) {
cout << "Output: The string is a palindrome." << endl;
} else {
cout << "Output: The string is not a palindrome." << endl;
}
cout << "-----------------------------------" << endl;
}
return 0;
}
# input: string of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void buildBadCharacterTable(const string& pattern, vector<int>& badCharTable) {
int m = pattern.length();
for (int i = 0; i < 256; i++) {
badCharTable[i] = m;
}
for (int i = 0; i < m - 1; i++) {
badCharTable[(int)pattern[i]] = m - i - 1;
}
}
int horspoolSearch(const string& text, const string& pattern) {
int n = text.length();
int m = pattern.length();
if (m == 0 || n < m) {
return -1;
}
vector<int> badCharTable(256, m);
buildBadCharacterTable(pattern, badCharTable);
int i = m - 1;
while (i < n) {
int j = m - 1;
while (j >= 0 && text[i] == pattern[j]) {
i--;
j--;
}
if (j < 0) {
return i + 1;
} else {
i += badCharTable[(int)text[i]];
}
}
return -1;
} | Two string of size m and n | O(n) | null | <s>[INST]void buildBadCharacterTable(const string& pattern, vector<int>& badCharTable) {
int m = pattern.length();
for (int i = 0; i < 256; i++) {
badCharTable[i] = m;
}
for (int i = 0; i < m - 1; i++) {
badCharTable[(int)pattern[i]] = m - i - 1;
}
}
int horspoolSearch(const string& text, const string& pattern) {
int n = text.length();
int m = pattern.length();
if (m == 0 || n < m) {
return -1;
}
vector<int> badCharTable(256, m);
buildBadCharacterTable(pattern, badCharTable);
int i = m - 1;
while (i < n) {
int j = m - 1;
while (j >= 0 && text[i] == pattern[j]) {
i--;
j--;
}
if (j < 0) {
return i + 1;
} else {
i += badCharTable[(int)text[i]];
}
}
return -1;
}# input: Two string of size m and n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void buildBadCharacterTable(const string& pattern, vector<int>& badCharTable) {
int m = pattern.length();
for (int i = 0; i < 256; i++) {
badCharTable[i] = -1;
}
for (int i = 0; i < m; i++) {
badCharTable[(int)pattern[i]] = i;
}
}
void buildGoodSuffixTable(const string& pattern, vector<int>& goodSuffixTable) {
int m = pattern.length();
goodSuffixTable.assign(m, m);
vector<int> border(m + 1, 0);
int i = m, j = m + 1;
border[i] = j;
while (i > 0) {
while (j <= m && pattern[i - 1] != pattern[j - 1]) {
if (goodSuffixTable[j] == m) {
goodSuffixTable[j] = j - i;
}
j = border[j];
}
i--;
j--;
border[i] = j;
}
j = border[0];
for (i = 0; i <= m; i++) {
if (goodSuffixTable[i] == m) {
goodSuffixTable[i] = j;
}
if (i == j) {
j = border[j];
}
}
}
int boyerMooreSearch(const string& text, const string& pattern) {
int n = text.length();
int m = pattern.length();
if (m == 0 || n < m) {
return -1;
}
vector<int> badCharTable(256, -1);
vector<int> goodSuffixTable(m, m);
buildBadCharacterTable(pattern, badCharTable);
buildGoodSuffixTable(pattern, goodSuffixTable);
int i = m - 1;
while (i < n) {
int j = m - 1;
while (j >= 0 && text[i] == pattern[j]) {
i--;
j--;
}
if (j < 0) {
return i + 1;
} else {
int badCharShift = j - badCharTable[(int)text[i]];
int goodSuffixShift = goodSuffixTable[j + 1];
i += max(badCharShift, goodSuffixShift);
}
}
return -1;
} | Two string of size m and n | O(n) | null | <s>[INST]void buildBadCharacterTable(const string& pattern, vector<int>& badCharTable) {
int m = pattern.length();
for (int i = 0; i < 256; i++) {
badCharTable[i] = -1;
}
for (int i = 0; i < m; i++) {
badCharTable[(int)pattern[i]] = i;
}
}
void buildGoodSuffixTable(const string& pattern, vector<int>& goodSuffixTable) {
int m = pattern.length();
goodSuffixTable.assign(m, m);
vector<int> border(m + 1, 0);
int i = m, j = m + 1;
border[i] = j;
while (i > 0) {
while (j <= m && pattern[i - 1] != pattern[j - 1]) {
if (goodSuffixTable[j] == m) {
goodSuffixTable[j] = j - i;
}
j = border[j];
}
i--;
j--;
border[i] = j;
}
j = border[0];
for (i = 0; i <= m; i++) {
if (goodSuffixTable[i] == m) {
goodSuffixTable[i] = j;
}
if (i == j) {
j = border[j];
}
}
}
int boyerMooreSearch(const string& text, const string& pattern) {
int n = text.length();
int m = pattern.length();
if (m == 0 || n < m) {
return -1;
}
vector<int> badCharTable(256, -1);
vector<int> goodSuffixTable(m, m);
buildBadCharacterTable(pattern, badCharTable);
buildGoodSuffixTable(pattern, goodSuffixTable);
int i = m - 1;
while (i < n) {
int j = m - 1;
while (j >= 0 && text[i] == pattern[j]) {
i--;
j--;
}
if (j < 0) {
return i + 1;
} else {
int badCharShift = j - badCharTable[(int)text[i]];
int goodSuffixShift = goodSuffixTable[j + 1];
i += max(badCharShift, goodSuffixShift);
}
}
return -1;
}# input: Two string of size m and n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Knapsack {
private:
vector<vector<int>> memo;
public:
Knapsack(int n, int W) {
memo.resize(n + 1, vector<int>(W + 1, -1));
}
int knapsackRec(int n, int W, const vector<int>& values, const vector<int>& weights) {
if (n == 0 || W == 0) {
return 0;
}
if (memo[n][W] != -1) {
return memo[n][W];
}
if (weights[n - 1] > W) {
return memo[n][W] = knapsackRec(n - 1, W, values, weights);
} else {
int exclude = knapsackRec(n - 1, W, values, weights);
int include = values[n - 1] + knapsackRec(n - 1, W - weights[n - 1], values, weights);
return memo[n][W] = max(exclude, include);
}
}
};
| Two array of size m and n | O(n*m) | null | <s>[INST]class Knapsack {
private:
vector<vector<int>> memo;
public:
Knapsack(int n, int W) {
memo.resize(n + 1, vector<int>(W + 1, -1));
}
int knapsackRec(int n, int W, const vector<int>& values, const vector<int>& weights) {
if (n == 0 || W == 0) {
return 0;
}
if (memo[n][W] != -1) {
return memo[n][W];
}
if (weights[n - 1] > W) {
return memo[n][W] = knapsackRec(n - 1, W, values, weights);
} else {
int exclude = knapsackRec(n - 1, W, values, weights);
int include = values[n - 1] + knapsackRec(n - 1, W - weights[n - 1], values, weights);
return memo[n][W] = max(exclude, include);
}
}
};
# input: Two array of size m and n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '^') {
return 3;
}
return 0;
}
string infixToPostfix(const string& infix) {
stack<char> s;
string postfix;
for (char c : infix) {
if (isalnum(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
}
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
} | String of size n | O(n) | null | <s>[INST]bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '^') {
return 3;
}
return 0;
}
string infixToPostfix(const string& infix) {
stack<char> s;
string postfix;
for (char c : infix) {
if (isalnum(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
}
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <stack>
#include <cctype>
#include <string>
using namespace std;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
string postfixToInfix(const string& postfix) {
stack<string> s;
for (char c : postfix) {
if (isalnum(c)) {
s.push(string(1, c));
}
else if (isOperator(c)) {
string operand2 = s.top(); s.pop();
string operand1 = s.top(); s.pop();
string expr = "(" + operand1 + " " + c + " " + operand2 + ")";
s.push(expr);
}
}
return s.top();
}
int main() {
string postfix = "AB+C*D/";
string infix = postfixToInfix(postfix);
cout << "Postfix Expression: " << postfix << endl;
cout << "Infix Expression: " << infix << endl;
return 0;
}
| String of size n | O(n) | null | <s>[INST]#include <iostream>
#include <stack>
#include <cctype>
#include <string>
using namespace std;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
string postfixToInfix(const string& postfix) {
stack<string> s;
for (char c : postfix) {
if (isalnum(c)) {
s.push(string(1, c));
}
else if (isOperator(c)) {
string operand2 = s.top(); s.pop();
string operand1 = s.top(); s.pop();
string expr = "(" + operand1 + " " + c + " " + operand2 + ")";
s.push(expr);
}
}
return s.top();
}
int main() {
string postfix = "AB+C*D/";
string infix = postfixToInfix(postfix);
cout << "Postfix Expression: " << postfix << endl;
cout << "Infix Expression: " << infix << endl;
return 0;
}
# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class PrefixEvaluator {
public:
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
int evaluatePrefix(const string& prefix) {
stack<int> s;
for (int i = prefix.length() - 1; i >= 0; i--) {
char c = prefix[i];
if (isdigit(c)) {
s.push(c - '0');
}
else if (isOperator(c)) {
if (s.size() < 2) {
throw invalid_argument("Invalid prefix expression.");
}
int operand1 = s.top(); s.pop();
int operand2 = s.top(); s.pop();
int result = applyOperator(c, operand1, operand2);
s.push(result);
}
else {
throw invalid_argument("Invalid character in the prefix expression.");
}
}
if (s.size() != 1) {
throw invalid_argument("Invalid prefix expression.");
}
return s.top();
}
private:
int applyOperator(char op, int operand1, int operand2) {
switch (op) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
case '^': return pow(operand1, operand2);
default: throw invalid_argument("Unknown operator.");
}
}
}; | String of size n | O(n) | null | <s>[INST]class PrefixEvaluator {
public:
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
int evaluatePrefix(const string& prefix) {
stack<int> s;
for (int i = prefix.length() - 1; i >= 0; i--) {
char c = prefix[i];
if (isdigit(c)) {
s.push(c - '0');
}
else if (isOperator(c)) {
if (s.size() < 2) {
throw invalid_argument("Invalid prefix expression.");
}
int operand1 = s.top(); s.pop();
int operand2 = s.top(); s.pop();
int result = applyOperator(c, operand1, operand2);
s.push(result);
}
else {
throw invalid_argument("Invalid character in the prefix expression.");
}
}
if (s.size() != 1) {
throw invalid_argument("Invalid prefix expression.");
}
return s.top();
}
private:
int applyOperator(char op, int operand1, int operand2) {
switch (op) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
case '^': return pow(operand1, operand2);
default: throw invalid_argument("Unknown operator.");
}
}
};# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
| array of size n | O(n^2) | null | <s>[INST]def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
def fibonacci(n):
dp = [0, 1]
for i in range(2, n+1):
dp.append(dp[i-1] + dp[i-2])
return dp[n]
| integer n | O(n) | null | <s>[INST]def fibonacci(n):
dp = [0, 1]
for i in range(2, n+1):
dp.append(dp[i-1] + dp[i-2])
return dp[n]
# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
if self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
def kruskal(V, edges):
disjoint_set = DisjointSet(V)
mst = []
edges.sort(key=lambda edge: edge[2]) # Sort by weight
for u, v, weight in edges:
if disjoint_set.find(u) != disjoint_set.find(v):
mst.append((u, v, weight))
disjoint_set.union(u, v)
return mst | graph of E edges and V vertices | O(E log E) | null | <s>[INST]class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
if self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
def kruskal(V, edges):
disjoint_set = DisjointSet(V)
mst = []
edges.sort(key=lambda edge: edge[2]) # Sort by weight
for u, v, weight in edges:
if disjoint_set.find(u) != disjoint_set.find(v):
mst.append((u, v, weight))
disjoint_set.union(u, v)
return mst# input: graph of E edges and V vertices [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
def subsets(nums):
result = []
def backtrack(index, current):
result.append(current[:])
for i in range(index, len(nums)):
current.append(nums[i])
backtrack(i + 1, current)
current.pop()
backtrack(0, [])
return result
| array of size n | O(2^n) | null | <s>[INST]def subsets(nums):
result = []
def backtrack(index, current):
result.append(current[:])
for i in range(index, len(nums)):
current.append(nums[i])
backtrack(i + 1, current)
current.pop()
backtrack(0, [])
return result
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
def permute(nums):
result = []
def backtrack(first=0):
if first == len(nums):
result.append(nums[:])
for i in range(first, len(nums)):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
backtrack()
return result
| array of size n | O(n!) | null | <s>[INST]def permute(nums):
result = []
def backtrack(first=0):
if first == len(nums):
result.append(nums[:])
for i in range(first, len(nums)):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
backtrack()
return result
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
template <typename T>
class CircularBuffer {
private:
T* buffer;
int capacity;
int head;
int tail;
int size;
public:
CircularBuffer(int cap) : capacity(cap), head(0), tail(0), size(0) {
buffer = new T[capacity];
}
~CircularBuffer() {
delete[] buffer;
}
bool isFull() {
return size == capacity;
}
bool isEmpty() {
return size == 0;
}
void write(T value) {
if (isFull()) {
throw overflow_error("Buffer is full, cannot write more data.");
}
buffer[tail] = value;
tail = (tail + 1) % capacity;
}
T read() {
if (isEmpty()) {
throw underflow_error("Buffer is empty, nothing to read.");
}
T value = buffer[head];
head = (head + 1) % capacity;
size--;
return value;
}
int currentSize() {
return size;
}
int getCapacity() {
return capacity;
}
void display() {
if (isEmpty()) {
cout << "Buffer is empty!" << endl;
return;
}
cout << "Buffer contents: ";
for (int i = 0; i < size; i++) {
int index = (head + i) % capacity;
cout << buffer[index] << " ";
}
cout << endl;
}
}; | Array of size n | O(n) | null | <s>[INST]template <typename T>
class CircularBuffer {
private:
T* buffer;
int capacity;
int head;
int tail;
int size;
public:
CircularBuffer(int cap) : capacity(cap), head(0), tail(0), size(0) {
buffer = new T[capacity];
}
~CircularBuffer() {
delete[] buffer;
}
bool isFull() {
return size == capacity;
}
bool isEmpty() {
return size == 0;
}
void write(T value) {
if (isFull()) {
throw overflow_error("Buffer is full, cannot write more data.");
}
buffer[tail] = value;
tail = (tail + 1) % capacity;
}
T read() {
if (isEmpty()) {
throw underflow_error("Buffer is empty, nothing to read.");
}
T value = buffer[head];
head = (head + 1) % capacity;
size--;
return value;
}
int currentSize() {
return size;
}
int getCapacity() {
return capacity;
}
void display() {
if (isEmpty()) {
cout << "Buffer is empty!" << endl;
return;
}
cout << "Buffer contents: ";
for (int i = 0; i < size; i++) {
int index = (head + i) % capacity;
cout << buffer[index] << " ";
}
cout << endl;
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def romanToInt(self, s: str) -> int:
number=0
hashmap={
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
for i in range(0,len(s)):
if i<len(s)-1 and hashmap[s[i]]<hashmap[s[i+1]]:
number-=hashmap[s[i]]
else:
number+=hashmap[s[i]]
return number
| string of length n | O(n) | null | <s>[INST]class Solution:
def romanToInt(self, s: str) -> int:
number=0
hashmap={
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
for i in range(0,len(s)):
if i<len(s)-1 and hashmap[s[i]]<hashmap[s[i+1]]:
number-=hashmap[s[i]]
else:
number+=hashmap[s[i]]
return number
# input: string of length n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
row=[1]*n
for i in range(0,m-1):
new_row=[1]*n
for j in range(n-2,-1,-1):
new_row[j]=new_row[j+1]+row[j]
row=new_row
return row[0]
| integers n and m | O(m*n) | null | <s>[INST]class Solution:
def uniquePaths(self, m: int, n: int) -> int:
row=[1]*n
for i in range(0,m-1):
new_row=[1]*n
for j in range(n-2,-1,-1):
new_row[j]=new_row[j+1]+row[j]
row=new_row
return row[0]
# input: integers n and m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void heapify(int *h,int n){
int i,j,k,heap,v;
for(i=n/2;i>=1;i--){
k=i;
heap=0;
v=h[k];
while(!heap && 2*k<=n){
j=2*k;
if(j<n && h[j]<h[j+1]){
j=j+1;
}
else if(v>=h[j]){
heap=1;
}
else{
h[k]=h[j];
k=j;
}
}
h[k]=v;
}
}
int findKthLargest(int* nums, int numsSize, int k) {
heapify(nums,numsSize);
int kthlar;
for(int i=1;i<=k;i++){
kthlar=nums[0];
nums[0]=nums[numsSize-1];
numsSize--;
heapify(nums,numsSize);
}
return kthlar;
} | array of size n | O(n*log(n)) | null | <s>[INST]void heapify(int *h,int n){
int i,j,k,heap,v;
for(i=n/2;i>=1;i--){
k=i;
heap=0;
v=h[k];
while(!heap && 2*k<=n){
j=2*k;
if(j<n && h[j]<h[j+1]){
j=j+1;
}
else if(v>=h[j]){
heap=1;
}
else{
h[k]=h[j];
k=j;
}
}
h[k]=v;
}
}
int findKthLargest(int* nums, int numsSize, int k) {
heapify(nums,numsSize);
int kthlar;
for(int i=1;i<=k;i++){
kthlar=nums[0];
nums[0]=nums[numsSize-1];
numsSize--;
heapify(nums,numsSize);
}
return kthlar;
}# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
LIS=[1]*len(nums)
for i in range(len(nums)-1,-1,-1):
for j in range(i+1,len(nums)):
if nums[i]<nums[j]:
LIS[i]=max(LIS[i],1+LIS[j])
return max(LIS)
| array of size n | O(n^2) | null | <s>[INST]class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
LIS=[1]*len(nums)
for i in range(len(nums)-1,-1,-1):
for j in range(i+1,len(nums)):
if nums[i]<nums[j]:
LIS[i]=max(LIS[i],1+LIS[j])
return max(LIS)
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
void decimalToBinary(int n) {
if (n == 0) {
cout << "0";
return;
}
vector<int> binary;
while (n > 0) {
binary.push_back(n % 2);
n = n / 2;
}
reverse(binary.begin(), binary.end());
for (int bit : binary) {
cout << bit;
}
cout << endl;
} | integer n | O(n) | null | <s>[INST]void decimalToBinary(int n) {
if (n == 0) {
cout << "0";
return;
}
vector<int> binary;
while (n > 0) {
binary.push_back(n % 2);
n = n / 2;
}
reverse(binary.begin(), binary.end());
for (int bit : binary) {
cout << bit;
}
cout << endl;
}# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int binaryToDecimal(const string& binary) {
int decimal = 0;
int length = binary.length();
for (int i = 0; i < length; i++) {
if (binary[i] == '1') {
decimal += pow(2, length - 1 - i);
}
}
return decimal;
} | String of size n | O(n) | null | <s>[INST]int binaryToDecimal(const string& binary) {
int decimal = 0;
int length = binary.length();
for (int i = 0; i < length; i++) {
if (binary[i] == '1') {
decimal += pow(2, length - 1 - i);
}
}
return decimal;
}# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Node {
public:
string value;
Node* left;
Node* right;
Node(string val) : value(val), left(nullptr), right(nullptr) {}
};
class ExpressionTree {
public:
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
Node* createExpressionTree(const string& infix) {
stack<Node*> operands;
stack<char> operators;
for (int i = 0; i < infix.length(); ++i) {
char current = infix[i];
if (current == ' ') continue;
if (isalnum(current)) {
operands.push(new Node(string(1, current)));
}
else if (current == '(') {
operators.push(current);
}
else if (current == ')') {
while (!operators.empty() && operators.top() != '(') {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
operators.pop(); }
else if (isOperator(current)) {
while (!operators.empty() && precedence(operators.top()) >= precedence(current)) {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
operators.push(current);
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
return operands.top();
}
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->value << " ";
inorder(root->right);
}
}
}; | String of size n | O(n) | null | <s>[INST]class Node {
public:
string value;
Node* left;
Node* right;
Node(string val) : value(val), left(nullptr), right(nullptr) {}
};
class ExpressionTree {
public:
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
Node* createExpressionTree(const string& infix) {
stack<Node*> operands;
stack<char> operators;
for (int i = 0; i < infix.length(); ++i) {
char current = infix[i];
if (current == ' ') continue;
if (isalnum(current)) {
operands.push(new Node(string(1, current)));
}
else if (current == '(') {
operators.push(current);
}
else if (current == ')') {
while (!operators.empty() && operators.top() != '(') {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
operators.pop(); }
else if (isOperator(current)) {
while (!operators.empty() && precedence(operators.top()) >= precedence(current)) {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
operators.push(current);
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
Node* right = operands.top();
operands.pop();
Node* left = operands.top();
operands.pop();
Node* opNode = new Node(string(1, op));
opNode->left = left;
opNode->right = right;
operands.push(opNode);
}
return operands.top();
}
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->value << " ";
inorder(root->right);
}
}
};# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Node {
public:
int value;
Node* left;
Node* right;
Node(int val) : value(val), left(nullptr), right(nullptr) {}
};
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->value << " ";
inorder(root->right);
}
}
void preorder(Node* root) {
if (root != nullptr) {
cout << root->value << " ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(Node* root) {
if (root != nullptr) {
postorder(root->left);
postorder(root->right);
cout << root->value << " ";
}
}
void levelOrder(Node* root) {
if (root == nullptr) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
q.pop();
cout << current->value << " ";
if (current->left != nullptr) {
q.push(current->left);
}
if (current->right != nullptr) {
q.push(current->right);
}
}
} | array of size n | O(n) | null | <s>[INST]class Node {
public:
int value;
Node* left;
Node* right;
Node(int val) : value(val), left(nullptr), right(nullptr) {}
};
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->value << " ";
inorder(root->right);
}
}
void preorder(Node* root) {
if (root != nullptr) {
cout << root->value << " ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(Node* root) {
if (root != nullptr) {
postorder(root->left);
postorder(root->right);
cout << root->value << " ";
}
}
void levelOrder(Node* root) {
if (root == nullptr) return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
q.pop();
cout << current->value << " ";
if (current->left != nullptr) {
q.push(current->left);
}
if (current->right != nullptr) {
q.push(current->right);
}
}
}# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int integerBreak(int n) {
unordered_map<int,int> memo;
memo[1]=0;
memo[2]=1;
return count(n,memo);
}
int count(int n,unordered_map<int,int>& memo){
if(memo.find(n)!=memo.end()){
return memo[n];
}
int value=1;
for(int i=2;i<n;i++){
value=max(value,max(i*(n-i),i*count(n-i,memo)));
}
memo[n]=value;
return memo[n];
}
int max(int a,int b){
return a>b?a:b;
}
}; | integer n | O(n^2) | null | <s>[INST]class Solution {
public:
int integerBreak(int n) {
unordered_map<int,int> memo;
memo[1]=0;
memo[2]=1;
return count(n,memo);
}
int count(int n,unordered_map<int,int>& memo){
if(memo.find(n)!=memo.end()){
return memo[n];
}
int value=1;
for(int i=2;i<n;i++){
value=max(value,max(i*(n-i),i*count(n-i,memo)));
}
memo[n]=value;
return memo[n];
}
int max(int a,int b){
return a>b?a:b;
}
};# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution:
def __init__(self, nums: List[int]):
self.nums=nums
self.trace=nums[:]
def reset(self) -> List[int]:
# self.nums=self.trace
return self.trace
def shuffle(self) -> List[int]:
random.shuffle(self.nums)
return self.nums
| array of size n | O(n) | null | <s>[INST]class Solution:
def __init__(self, nums: List[int]):
self.nums=nums
self.trace=nums[:]
def reset(self) -> List[int]:
# self.nums=self.trace
return self.trace
def shuffle(self) -> List[int]:
random.shuffle(self.nums)
return self.nums
# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int integerReplacement(int n) {
unordered_map<long long,long long> cache;
cache[1]=0;
return helper(n,cache);
}
long long helper(long long n,unordered_map<long long,long long>& cache){
if(cache.find(n)!=cache.end()){
return cache[n];
}
if(n%2==0){
cache[n]=1+helper(n/2,cache);
}
else{
cache[n]=1+mini(helper(n+1,cache),helper(n-1,cache));
}
return cache[n];
}
long long mini(long long x,long long y){
return x>y?y:x;
}
}; | integer n | O(n) | null | <s>[INST]class Solution {
public:
int integerReplacement(int n) {
unordered_map<long long,long long> cache;
cache[1]=0;
return helper(n,cache);
}
long long helper(long long n,unordered_map<long long,long long>& cache){
if(cache.find(n)!=cache.end()){
return cache[n];
}
if(n%2==0){
cache[n]=1+helper(n/2,cache);
}
else{
cache[n]=1+mini(helper(n+1,cache),helper(n-1,cache));
}
return cache[n];
}
long long mini(long long x,long long y){
return x>y?y:x;
}
};# input: integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
string removeKdigits(string num, int k) {
vector<char> st;
if(num.size()==k){
return "0";
}
for(auto x:num){
if(st.empty()){
st.push_back(x);
}
else{
if(x>=st.back()){
st.push_back(x);
}
else{
while(!st.empty() && x<st.back() && k>0){
st.pop_back();
k--;
}
st.push_back(x);
}
}
}
if(k!=0){
while(!st.empty() && k>0){
st.pop_back();
k--;
}
}
string answer="";
int i=0;
while(i<st.size()){
if(i==0 && st[i]=='0'){
while(i<st.size() && st[i]=='0')
i++;
}
if(i==st.size()){
return "0";
}
else{
answer+=st[i];
i++;
}
}
return answer;
}
}; | string of length n | O(n) | null | <s>[INST]class Solution {
public:
string removeKdigits(string num, int k) {
vector<char> st;
if(num.size()==k){
return "0";
}
for(auto x:num){
if(st.empty()){
st.push_back(x);
}
else{
if(x>=st.back()){
st.push_back(x);
}
else{
while(!st.empty() && x<st.back() && k>0){
st.pop_back();
k--;
}
st.push_back(x);
}
}
}
if(k!=0){
while(!st.empty() && k>0){
st.pop_back();
k--;
}
}
string answer="";
int i=0;
while(i<st.size()){
if(i==0 && st[i]=='0'){
while(i<st.size() && st[i]=='0')
i++;
}
if(i==st.size()){
return "0";
}
else{
answer+=st[i];
i++;
}
}
return answer;
}
};# input: string of length n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution{
int maximum(int a,int b){
return a>b?a:b;
}
}; | 2 integers | O(1) | null | <s>[INST]class Solution{
int maximum(int a,int b){
return a>b?a:b;
}
};# input: 2 integers [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
arr = [10, 20, 30, 40]
element = arr[2]
print(element) | array of size n | O(1) | null | <s>[INST]arr = [10, 20, 30, 40]
element = arr[2]
print(element)# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode();
ListNode* curr = ans;
int carry=0;
while(l1!=NULL && l2!=NULL){
ListNode* temp = new ListNode();
temp->val = l1->val+l2->val+carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l1 = l1->next;
l2 = l2->next;
}
if(l1!=NULL){
while(l1!=NULL){
ListNode* temp = new ListNode();
temp->val = l1->val + carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l1 = l1->next;
}
}
else{
while(l2!=NULL){
ListNode* temp = new ListNode();
temp->val = l2->val + carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l2 = l2->next;
}
}
if(carry==1){
ListNode* temp = new ListNode();
temp->val = 1;
curr->next = temp;
}
return ans->next;
}
}; | Two linked lists of length n and m | O(n+m) | null | <s>[INST]class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode();
ListNode* curr = ans;
int carry=0;
while(l1!=NULL && l2!=NULL){
ListNode* temp = new ListNode();
temp->val = l1->val+l2->val+carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l1 = l1->next;
l2 = l2->next;
}
if(l1!=NULL){
while(l1!=NULL){
ListNode* temp = new ListNode();
temp->val = l1->val + carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l1 = l1->next;
}
}
else{
while(l2!=NULL){
ListNode* temp = new ListNode();
temp->val = l2->val + carry;
if(temp->val>=10){
carry = 1;
temp->val = (temp->val)%10;
}
else
carry=0;
curr->next = temp;
curr = curr->next;
l2 = l2->next;
}
}
if(carry==1){
ListNode* temp = new ListNode();
temp->val = 1;
curr->next = temp;
}
return ans->next;
}
};# input: Two linked lists of length n and m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
string longestPalindrome(string s) {
int start =0,size = 0;
int cur = 0;
int left =0,right=0;
for(int i=0;i<s.length();i++){
left = i-1;
right = i+1;
cur = 1;
while(s[i]==s[right]){
right++;
cur++;
}
while(left>=0 && right<s.length()){
if(s[left]==s[right]){
left--;
right++;
cur +=2;
}
else{
break;
}
}
left++;
right--;
if(cur>size){
start = left;
size = cur;
}
}
return s.substr(start,size);
}
}; | String of length N | O(n) | null | <s>[INST]class Solution {
public:
string longestPalindrome(string s) {
int start =0,size = 0;
int cur = 0;
int left =0,right=0;
for(int i=0;i<s.length();i++){
left = i-1;
right = i+1;
cur = 1;
while(s[i]==s[right]){
right++;
cur++;
}
while(left>=0 && right<s.length()){
if(s[left]==s[right]){
left--;
right++;
cur +=2;
}
else{
break;
}
}
left++;
right--;
if(cur>size){
start = left;
size = cur;
}
}
return s.substr(start,size);
}
};# input: String of length N [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <climits>
using namespace std;
class Solution {
public:
int reverse(int x) {
long ans = 0;
bool neg = false;
if(abs(x)>=INT_MAX-1 && x<0)
return 0;
if(x<0){
x=x*-1;
neg = true;
}
while(x>0){
ans = ans*10 + x%10;
x = x/10;
if((neg==false && ans>INT_MAX-1) || (neg==true && ans>INT_MAX)){
ans = 0;
break;
}
}
if(neg)
return ans*-1;
else
return ans;
}
};
int main() {
Solution solution;
int x = -123;
cout << solution.reverse(x) << endl;
return 0;
}
| integer of n digits | O(n) | null | <s>[INST]#include <iostream>
#include <climits>
using namespace std;
class Solution {
public:
int reverse(int x) {
long ans = 0;
bool neg = false;
if(abs(x)>=INT_MAX-1 && x<0)
return 0;
if(x<0){
x=x*-1;
neg = true;
}
while(x>0){
ans = ans*10 + x%10;
x = x/10;
if((neg==false && ans>INT_MAX-1) || (neg==true && ans>INT_MAX)){
ans = 0;
break;
}
}
if(neg)
return ans*-1;
else
return ans;
}
};
int main() {
Solution solution;
int x = -123;
cout << solution.reverse(x) << endl;
return 0;
}
# input: integer of n digits [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if(nums.size()<4)
return {};
long tar = target;
sort(nums.begin(),nums.end());
vector<vector<int>> ans;
int i = 0,j=0,k=0,l=0;
set<vector<int>> st;
while(i<nums.size()-3){
j = i+1;
long sum = nums[i];
while(j<(nums.size()-2)){
sum+=nums[j];
k = j+1;
l = nums.size()-1;
while(k<l){
if((sum+nums[k]+nums[l])==tar){
vector<int> temp = {nums[i],nums[j],nums[k],nums[l]};
st.insert(temp);
k++;
l--;
}
else if(sum+nums[k]+nums[l]<tar){
k++;
}
else
l--;
}
sum = sum-nums[j];
j++;
}
i++;
}
for(auto it:st)
ans.push_back(it);
return ans;
}
}; | Array of size n | O(n^3) | null | <s>[INST]class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if(nums.size()<4)
return {};
long tar = target;
sort(nums.begin(),nums.end());
vector<vector<int>> ans;
int i = 0,j=0,k=0,l=0;
set<vector<int>> st;
while(i<nums.size()-3){
j = i+1;
long sum = nums[i];
while(j<(nums.size()-2)){
sum+=nums[j];
k = j+1;
l = nums.size()-1;
while(k<l){
if((sum+nums[k]+nums[l])==tar){
vector<int> temp = {nums[i],nums[j],nums[k],nums[l]};
st.insert(temp);
k++;
l--;
}
else if(sum+nums[k]+nums[l]<tar){
k++;
}
else
l--;
}
sum = sum-nums[j];
j++;
}
i++;
}
for(auto it:st)
ans.push_back(it);
return ans;
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int minimumTime(vector<vector<int>>& grid) {
if (grid[0][1] > 1 && grid[1][0] > 1) {
return -1;
}
int rows = grid.size(), cols = grid[0].size();
vector<vector<int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
priority_queue<vector<int>, vector<vector<int>>, greater<>> pq;
pq.push({grid[0][0], 0, 0});
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
int time = curr[0], row = curr[1], col = curr[2];
if (row == rows - 1 && col == cols - 1) {
return time;
}
if (visited[row][col]) {
continue;
}
visited[row][col] = true;
for (auto& d : directions) {
int nextRow = row + d[0], nextCol = col + d[1];
if (!isValid(visited, nextRow, nextCol)) {
continue;
}
int waitTime =
((grid[nextRow][nextCol] - time) % 2 == 0) ? 1 : 0;
int nextTime = max(grid[nextRow][nextCol] + waitTime, time + 1);
pq.push({nextTime, nextRow, nextCol});
}
}
return -1;
}
private:
bool isValid(vector<vector<bool>>& visited, int row, int col) {
return row >= 0 && col >= 0 && row < visited.size() &&
col < visited[0].size() && !visited[row][col];
}
};
| Matrix of size m*n | O(m*nlog(m*n)) | null | <s>[INST]class Solution {
public:
int minimumTime(vector<vector<int>>& grid) {
if (grid[0][1] > 1 && grid[1][0] > 1) {
return -1;
}
int rows = grid.size(), cols = grid[0].size();
vector<vector<int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
vector<vector<bool>> visited(rows, vector<bool>(cols, false));
priority_queue<vector<int>, vector<vector<int>>, greater<>> pq;
pq.push({grid[0][0], 0, 0});
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
int time = curr[0], row = curr[1], col = curr[2];
if (row == rows - 1 && col == cols - 1) {
return time;
}
if (visited[row][col]) {
continue;
}
visited[row][col] = true;
for (auto& d : directions) {
int nextRow = row + d[0], nextCol = col + d[1];
if (!isValid(visited, nextRow, nextCol)) {
continue;
}
int waitTime =
((grid[nextRow][nextCol] - time) % 2 == 0) ? 1 : 0;
int nextTime = max(grid[nextRow][nextCol] + waitTime, time + 1);
pq.push({nextTime, nextRow, nextCol});
}
}
return -1;
}
private:
bool isValid(vector<vector<bool>>& visited, int row, int col) {
return row >= 0 && col >= 0 && row < visited.size() &&
col < visited[0].size() && !visited[row][col];
}
};
# input: Matrix of size m*n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
private:
vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public:
int minimumObstacles(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> minObstacles(m, vector<int>(n, INT_MAX));
minObstacles[0][0] = 0;
deque<array<int, 3>> deque;
deque.push_back({0, 0, 0});
while (!deque.empty()) {
auto current = deque.front();
deque.pop_front();
int obstacles = current[0], row = current[1], col = current[2];
for (auto& dir : directions) {
int newRow = row + dir[0], newCol = col + dir[1];
if (isValid(grid, newRow, newCol) && minObstacles[newRow][newCol] == INT_MAX) {
if (grid[newRow][newCol] == 1) {
minObstacles[newRow][newCol] = obstacles + 1;
deque.push_back({obstacles + 1, newRow, newCol});
} else {
minObstacles[newRow][newCol] = obstacles;
deque.push_front({obstacles, newRow, newCol});
}
}
}
}
return minObstacles[m - 1][n - 1];
}
private:
bool isValid(vector<vector<int>>& grid, int row, int col) {
return row >= 0 && col >= 0 && row < grid.size() && col < grid[0].size();
}
};
| matrix of size m*n | O(m*n) | null | <s>[INST]class Solution {
private:
vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public:
int minimumObstacles(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> minObstacles(m, vector<int>(n, INT_MAX));
minObstacles[0][0] = 0;
deque<array<int, 3>> deque;
deque.push_back({0, 0, 0});
while (!deque.empty()) {
auto current = deque.front();
deque.pop_front();
int obstacles = current[0], row = current[1], col = current[2];
for (auto& dir : directions) {
int newRow = row + dir[0], newCol = col + dir[1];
if (isValid(grid, newRow, newCol) && minObstacles[newRow][newCol] == INT_MAX) {
if (grid[newRow][newCol] == 1) {
minObstacles[newRow][newCol] = obstacles + 1;
deque.push_back({obstacles + 1, newRow, newCol});
} else {
minObstacles[newRow][newCol] = obstacles;
deque.push_front({obstacles, newRow, newCol});
}
}
}
}
return minObstacles[m - 1][n - 1];
}
private:
bool isValid(vector<vector<int>>& grid, int row, int col) {
return row >= 0 && col >= 0 && row < grid.size() && col < grid[0].size();
}
};
# input: matrix of size m*n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class Solution {
int minMinutes = INT_MAX;
public:
int takeCharacters(string s, int k) {
if (k == 0) return 0;
vector<int> count(3, 0);
solve(s, k, 0, s.length() - 1, count, 0);
return minMinutes == INT_MAX ? -1 : minMinutes;
}
private:
void solve(string& s, int k, int left, int right, vector<int> count, int minutes) {
if (count[0] >= k && count[1] >= k && count[2] >= k) {
minMinutes = min(minMinutes, minutes);
return;
}
if (left > right) return;
vector<int> leftCount = count;
leftCount[s[left] - 'a']++;
solve(s, k, left + 1, right, leftCount, minutes + 1);
vector<int> rightCount = count;
rightCount[s[right] - 'a']++;
solve(s, k, left, right - 1, rightCount, minutes + 1);
}
};
int main() {
Solution solution;
string s = "aabbcc";
int k = 2;
cout << solution.takeCharacters(s, k) << endl;
return 0;
}
| String of length N | O(2^n) | null | <s>[INST]#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class Solution {
int minMinutes = INT_MAX;
public:
int takeCharacters(string s, int k) {
if (k == 0) return 0;
vector<int> count(3, 0);
solve(s, k, 0, s.length() - 1, count, 0);
return minMinutes == INT_MAX ? -1 : minMinutes;
}
private:
void solve(string& s, int k, int left, int right, vector<int> count, int minutes) {
if (count[0] >= k && count[1] >= k && count[2] >= k) {
minMinutes = min(minMinutes, minutes);
return;
}
if (left > right) return;
vector<int> leftCount = count;
leftCount[s[left] - 'a']++;
solve(s, k, left + 1, right, leftCount, minutes + 1);
vector<int> rightCount = count;
rightCount[s[right] - 'a']++;
solve(s, k, left, right - 1, rightCount, minutes + 1);
}
};
int main() {
Solution solution;
string s = "aabbcc";
int k = 2;
cout << solution.takeCharacters(s, k) << endl;
return 0;
}
# input: String of length N [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int findChampion(int n, vector<vector<int>>& edges) {
vector<int> adj(n,0);
for(int i=0;i<edges.size();i++){
adj[edges[i][1]]++;
}
int ans = -1;
for(int i=0;i<n;i++){
if(adj[i]==0){
if(ans!=-1)
return -1;
else
ans = i;
}
}
return ans;
}
}; | number of vertices v and edge matrix of size v | O(v) | null | <s>[INST]class Solution {
public:
int findChampion(int n, vector<vector<int>>& edges) {
vector<int> adj(n,0);
for(int i=0;i<edges.size();i++){
adj[edges[i][1]]++;
}
int ans = -1;
for(int i=0;i<n;i++){
if(adj[i]==0){
if(ans!=-1)
return -1;
else
ans = i;
}
}
return ans;
}
};# input: number of vertices v and edge matrix of size v [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int search(vector<int>& nums, int target){
int end = nums.size() - 1;
int beg = 0;
int mid;
while (end >= beg) {
mid = (end + beg) / 2;
if (target == nums[mid]) {
return mid;
}
else if ( target > nums[mid]) {
if( target<=nums[end] || nums[end]<nums[mid])
beg = mid+1;
else
end = mid-1;
}else if (target < nums[mid]) {
if(target>=nums[beg] || nums[beg]>nums[mid])
end = mid-1;
else
beg=mid+1;
}
}
return -1;
}
}; | Array of size n | O(log n) | null | <s>[INST]class Solution {
public:
int search(vector<int>& nums, int target){
int end = nums.size() - 1;
int beg = 0;
int mid;
while (end >= beg) {
mid = (end + beg) / 2;
if (target == nums[mid]) {
return mid;
}
else if ( target > nums[mid]) {
if( target<=nums[end] || nums[end]<nums[mid])
beg = mid+1;
else
end = mid-1;
}else if (target < nums[mid]) {
if(target>=nums[beg] || nums[beg]>nums[mid])
end = mid-1;
else
beg=mid+1;
}
}
return -1;
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(),1);
for(int i=1;i<nums.size();i++){
int j=0;
while(j<i){
if(nums[i]>nums[j])
dp[i] = max(dp[i],1+dp[j]);
j++;
}
}
int ans = 0;
for(auto it:dp){
if(it>ans)
ans = it;
}
return ans;
}
}; | Array of size n | O(n^2) | null | <s>[INST]class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(),1);
for(int i=1;i<nums.size();i++){
int j=0;
while(j<i){
if(nums[i]>nums[j])
dp[i] = max(dp[i],1+dp[j]);
j++;
}
}
int ans = 0;
for(auto it:dp){
if(it>ans)
ans = it;
}
return ans;
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class Solution {
public:
bool isMatch(string s, string p) {
int n=s.length(),m=p.length();
vector<bool>prev(m+1,false),cur(m+1,false);
prev[0]=true;
for(int i=1;i<=m;i++)
{
if(p[i-1]=='*')
prev[i]=true;
else
break;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s[i-1]==p[j-1] || p[j-1]=='?')
cur[j]=prev[j-1];
else if(p[j-1]=='*')
cur[j]=cur[j-1] || prev[j];
else
cur[j]=false;
}
prev=cur;
}
return prev[m];
}
}; | two strings of size n and m | O(n*m) | null | <s>[INST]class Solution {
public:
bool isMatch(string s, string p) {
int n=s.length(),m=p.length();
vector<bool>prev(m+1,false),cur(m+1,false);
prev[0]=true;
for(int i=1;i<=m;i++)
{
if(p[i-1]=='*')
prev[i]=true;
else
break;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s[i-1]==p[j-1] || p[j-1]=='?')
cur[j]=prev[j-1];
else if(p[j-1]=='*')
cur[j]=cur[j-1] || prev[j];
else
cur[j]=false;
}
prev=cur;
}
return prev[m];
}
};# input: two strings of size n and m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
vector<int> spiralTraverse(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty()) return result;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (top <= bottom && left <= right) {
// Traverse right
for (int j = left; j <= right; j++)
result.push_back(matrix[top][j]);
top++;
// Traverse down
for (int i = top; i <= bottom; i++)
result.push_back(matrix[i][right]);
right--;
if (top <= bottom) {
// Traverse left
for (int j = right; j >= left; j--)
result.push_back(matrix[bottom][j]);
bottom--;
}
if (left <= right) {
// Traverse up
for (int i = bottom; i >= top; i--)
result.push_back(matrix[i][left]);
left++;
}
}
return result;
} | Matrix of size m*n | O(m*n) | null | <s>[INST]vector<int> spiralTraverse(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.empty()) return result;
int top = 0, bottom = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (top <= bottom && left <= right) {
// Traverse right
for (int j = left; j <= right; j++)
result.push_back(matrix[top][j]);
top++;
// Traverse down
for (int i = top; i <= bottom; i++)
result.push_back(matrix[i][right]);
right--;
if (top <= bottom) {
// Traverse left
for (int j = right; j >= left; j--)
result.push_back(matrix[bottom][j]);
bottom--;
}
if (left <= right) {
// Traverse up
for (int i = bottom; i >= top; i--)
result.push_back(matrix[i][left]);
left++;
}
}
return result;
}# input: Matrix of size m*n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
bool matchPattern(string& text, string& pattern) {
int m = text.length(), n = pattern.length();
for (int i = 0; i <= m - n; i++) {
bool match = true;
for (int j = 0; j < n; j++) {
if (text[i + j] != pattern[j]) {
match = false;
break;
}
}
if (match) return true;
}
return false;
} | two strings of size n and m | O(n*m) | null | <s>[INST]bool matchPattern(string& text, string& pattern) {
int m = text.length(), n = pattern.length();
for (int i = 0; i <= m - n; i++) {
bool match = true;
for (int j = 0; j < n; j++) {
if (text[i + j] != pattern[j]) {
match = false;
break;
}
}
if (match) return true;
}
return false;
}# input: two strings of size n and m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
vector<int> getPrimeFactors(int n) {
vector<int> factors;
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
factors.push_back(i);
n /= i;
}
}
if (n > 1) factors.push_back(n);
return factors;
} | Integer n | O(sqrt(n)) | null | <s>[INST]vector<int> getPrimeFactors(int n) {
vector<int> factors;
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
factors.push_back(i);
n /= i;
}
}
if (n > 1) factors.push_back(n);
return factors;
}# input: Integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
vector<int> getColumnSums(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int rows = matrix.size(), cols = matrix[0].size();
vector<int> columnSums(cols, 0);
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
columnSums[j] += matrix[i][j];
}
}
return columnSums;
} | Matrix of size m*n | O(m*n) | null | <s>[INST]vector<int> getColumnSums(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int rows = matrix.size(), cols = matrix[0].size();
vector<int> columnSums(cols, 0);
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
columnSums[j] += matrix[i][j];
}
}
return columnSums;
}# input: Matrix of size m*n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int maxParenthesesDepth(string& s) {
int maxDepth = 0, currentDepth = 0;
for (char c : s) {
if (c == '(') {
currentDepth++;
maxDepth = max(maxDepth, currentDepth);
}
else if (c == ')') {
currentDepth--;
}
}
return maxDepth;
} | String of length N | O(n) | null | <s>[INST]int maxParenthesesDepth(string& s) {
int maxDepth = 0, currentDepth = 0;
for (char c : s) {
if (c == '(') {
currentDepth++;
maxDepth = max(maxDepth, currentDepth);
}
else if (c == ')') {
currentDepth--;
}
}
return maxDepth;
}# input: String of length N [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
bool canPartition(vector<int>& nums) {
int totalSum = 0;
for (int num : nums) totalSum += num;
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
for (int j = target; j >= num; j--) {
dp[j] |= dp[j - num];
}
}
return dp[target];
} | Array of size n | O(n*sum_of_array) | null | <s>[INST]bool canPartition(vector<int>& nums) {
int totalSum = 0;
for (int num : nums) totalSum += num;
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
for (int j = target; j >= num; j--) {
dp[j] |= dp[j - num];
}
}
return dp[target];
}# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
long long computeRollingHash(const string& s, int start, int length, long long prime = 31) {
long long hash = 0;
long long power = 1;
for (int i = 0; i < length; i++) {
hash = hash * prime + s[start + i];
if (i > 0) power *= prime;
}
return hash;
}
bool rabinKarpSearch(const string& text, const string& pattern) {
if (pattern.length() > text.length()) return false;
long long patternHash = computeRollingHash(pattern, 0, pattern.length());
long long textHash = computeRollingHash(text, 0, pattern.length());
for (int i = 0; i <= text.length() - pattern.length(); i++) {
if (patternHash == textHash) {
bool match = true;
for (int j = 0; j < pattern.length(); j++) {
if (text[i + j] != pattern[j]) {
match = false;
break;
}
}
if (match) return true;
}
if (i < text.length() - pattern.length()) {
textHash = (textHash - text[i] * pow(31, pattern.length() - 1)) * 31 + text[i + pattern.length()];
}
}
return false;
} | two strings of size n and m | O(n+m) | null | <s>[INST]long long computeRollingHash(const string& s, int start, int length, long long prime = 31) {
long long hash = 0;
long long power = 1;
for (int i = 0; i < length; i++) {
hash = hash * prime + s[start + i];
if (i > 0) power *= prime;
}
return hash;
}
bool rabinKarpSearch(const string& text, const string& pattern) {
if (pattern.length() > text.length()) return false;
long long patternHash = computeRollingHash(pattern, 0, pattern.length());
long long textHash = computeRollingHash(text, 0, pattern.length());
for (int i = 0; i <= text.length() - pattern.length(); i++) {
if (patternHash == textHash) {
bool match = true;
for (int j = 0; j < pattern.length(); j++) {
if (text[i + j] != pattern[j]) {
match = false;
break;
}
}
if (match) return true;
}
if (i < text.length() - pattern.length()) {
textHash = (textHash - text[i] * pow(31, pattern.length() - 1)) * 31 + text[i + pattern.length()];
}
}
return false;
}# input: two strings of size n and m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
long long computePolynomialCoefficient(int n, int k) {
if (k > n) return 0;
vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, 0));
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= min(i, k); j++) {
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}
}
return dp[n][k];
} | Two integers n and k | O(n*k) | null | <s>[INST]long long computePolynomialCoefficient(int n, int k) {
if (k > n) return 0;
vector<vector<long long>> dp(n + 1, vector<long long>(k + 1, 0));
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= min(i, k); j++) {
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}
}
return dp[n][k];
}# input: Two integers n and k [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int countSetBits(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
vector<int> countBitsInRange(int left, int right) {
vector<int> result;
for (int i = left; i <= right; i++) {
result.push_back(countSetBits(i));
}
return result;
} | Two integers i and j, where j-i = n | O(n*log(n)) | null | <s>[INST]int countSetBits(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
vector<int> countBitsInRange(int left, int right) {
vector<int> result;
for (int i = left; i <= right; i++) {
result.push_back(countSetBits(i));
}
return result;
}# input: Two integers i and j, where j-i = n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
int coinChangeMinCoins(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
} | Array of size n and integer amount m | O(n*m) | null | <s>[INST]int coinChangeMinCoins(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}# input: Array of size n and integer amount m [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
#include <iostream>
#include <vector>
#include <cmath>
#include <complex>
class ComplexNumber {
public:
double real, imag;
// Constructors
ComplexNumber(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Copy constructor
ComplexNumber(const ComplexNumber& other) : real(other.real), imag(other.imag) {}
// Arithmetic Operators
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(real + other.real, imag + other.imag);
}
ComplexNumber operator-(const ComplexNumber& other) const {
return ComplexNumber(real - other.real, imag - other.imag);
}
ComplexNumber operator*(const ComplexNumber& other) const {
return ComplexNumber(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
ComplexNumber operator/(const ComplexNumber& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return ComplexNumber(
(real * other.real + imag * other.imag) / denominator,
(imag * other.real - real * other.imag) / denominator
);
}
// Comparison Operators
bool operator==(const ComplexNumber& other) const {
const double EPSILON = 1e-9;
return (std::abs(real - other.real) < EPSILON) &&
(std::abs(imag - other.imag) < EPSILON);
}
// Additional Mathematical Methods
double magnitude() const {
return std::sqrt(real * real + imag * imag);
}
double argument() const {
return std::atan2(imag, real);
}
ComplexNumber conjugate() const {
return ComplexNumber(real, -imag);
}
// Print method
void print() const {
std::cout << real;
if (imag >= 0)
std::cout << " + " << imag << "i";
else
std::cout << " - " << std::abs(imag) << "i";
}
};
class FFT {
public:
// Fast Fourier Transform
static std::vector<ComplexNumber> transform(std::vector<ComplexNumber>& a, bool invert = false) {
int n = a.size();
// Bit reversal permutation
for (int i = 1, j = 0; i < n; i++) {
int bit = n >> 1;
for (; j & bit; bit >>= 1)
j ^= bit;
j ^= bit;
if (i < j)
std::swap(a[i], a[j]);
}
// Cooley-Tukey FFT algorithm
for (int len = 2; len <= n; len <<= 1) {
double ang = 2 * M_PI / len * (invert ? -1 : 1);
ComplexNumber wlen(std::cos(ang), std::sin(ang));
for (int i = 0; i < n; i += len) {
ComplexNumber w(1, 0);
for (int j = 0; j < len/2; j++) {
ComplexNumber u = a[i+j], v = a[i+j+len/2] * w;
a[i+j] = u + v;
a[i+j+len/2] = u - v;
w = w * wlen;
}
}
}
if (invert) {
for (ComplexNumber& x : a)
x = ComplexNumber(x.real / n, x.imag / n);
}
return a;
}
// Polynomial Multiplication using FFT
static std::vector<long long> multiplyPolynomials(
const std::vector<long long>& a,
const std::vector<long long>& b) {
// Find the next power of 2
int n = 1;
while (n < a.size() + b.size())
n <<= 1;
// Convert to complex numbers
std::vector<ComplexNumber> fa(n), fb(n);
for (size_t i = 0; i < a.size(); i++)
fa[i] = ComplexNumber(a[i], 0);
for (size_t i = 0; i < b.size(); i++)
fb[i] = ComplexNumber(b[i], 0);
// Transform both polynomials
fa = transform(fa);
fb = transform(fb);
// Multiply point-wise
for (int i = 0; i < n; i++)
fa[i] = fa[i] * fb[i];
// Inverse transform
fa = transform(fa, true);
// Convert back to integers
std::vector<long long> result(n);
for (int i = 0; i < n; i++)
result[i] = std::round(fa[i].real);
return result;
}
};
// Example usage and demonstration
int main() {
// Complex Number Operations
ComplexNumber a(3, 2); // 3 + 2i
ComplexNumber b(1, -1); // 1 - i
std::cout << "Complex Number Operations:\n";
std::cout << "a = "; a.print(); std::cout << std::endl;
std::cout << "b = "; b.print(); std::cout << std::endl;
ComplexNumber sum = a + b;
ComplexNumber diff = a - b;
ComplexNumber prod = a * b;
std::cout << "Sum (a + b) = "; sum.print(); std::cout << std::endl;
std::cout << "Difference (a - b) = "; diff.print(); std::cout << std::endl;
std::cout << "Product (a * b) = "; prod.print(); std::cout << std::endl;
std::cout << "\nComplex Number Properties:\n";
std::cout << "Magnitude of a: " << a.magnitude() << std::endl;
std::cout << "Argument of a: " << a.argument() << std::endl;
// Polynomial Multiplication Demonstration
std::vector<long long> poly1 = {1, 2, 3}; // 1 + 2x + 3x^2
std::vector<long long> poly2 = {4, 5, 6}; // 4 + 5x + 6x^2
std::cout << "\nPolynomial Multiplication:\n";
std::vector<long long> result = FFT::multiplyPolynomials(poly1, poly2);
std::cout << "Resulting Polynomial Coefficients:\n";
for (size_t i = 0; i < result.size(); i++) {
if (result[i] != 0) {
std::cout << result[i] << "x^" << i;
if (i < result.size() - 1) std::cout << " + ";
}
}
std::cout << std::endl;
return 0;
} | Array of size n | O(n*log(n)) | null | <s>[INST]#include <iostream>
#include <vector>
#include <cmath>
#include <complex>
class ComplexNumber {
public:
double real, imag;
// Constructors
ComplexNumber(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Copy constructor
ComplexNumber(const ComplexNumber& other) : real(other.real), imag(other.imag) {}
// Arithmetic Operators
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(real + other.real, imag + other.imag);
}
ComplexNumber operator-(const ComplexNumber& other) const {
return ComplexNumber(real - other.real, imag - other.imag);
}
ComplexNumber operator*(const ComplexNumber& other) const {
return ComplexNumber(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
ComplexNumber operator/(const ComplexNumber& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return ComplexNumber(
(real * other.real + imag * other.imag) / denominator,
(imag * other.real - real * other.imag) / denominator
);
}
// Comparison Operators
bool operator==(const ComplexNumber& other) const {
const double EPSILON = 1e-9;
return (std::abs(real - other.real) < EPSILON) &&
(std::abs(imag - other.imag) < EPSILON);
}
// Additional Mathematical Methods
double magnitude() const {
return std::sqrt(real * real + imag * imag);
}
double argument() const {
return std::atan2(imag, real);
}
ComplexNumber conjugate() const {
return ComplexNumber(real, -imag);
}
// Print method
void print() const {
std::cout << real;
if (imag >= 0)
std::cout << " + " << imag << "i";
else
std::cout << " - " << std::abs(imag) << "i";
}
};
class FFT {
public:
// Fast Fourier Transform
static std::vector<ComplexNumber> transform(std::vector<ComplexNumber>& a, bool invert = false) {
int n = a.size();
// Bit reversal permutation
for (int i = 1, j = 0; i < n; i++) {
int bit = n >> 1;
for (; j & bit; bit >>= 1)
j ^= bit;
j ^= bit;
if (i < j)
std::swap(a[i], a[j]);
}
// Cooley-Tukey FFT algorithm
for (int len = 2; len <= n; len <<= 1) {
double ang = 2 * M_PI / len * (invert ? -1 : 1);
ComplexNumber wlen(std::cos(ang), std::sin(ang));
for (int i = 0; i < n; i += len) {
ComplexNumber w(1, 0);
for (int j = 0; j < len/2; j++) {
ComplexNumber u = a[i+j], v = a[i+j+len/2] * w;
a[i+j] = u + v;
a[i+j+len/2] = u - v;
w = w * wlen;
}
}
}
if (invert) {
for (ComplexNumber& x : a)
x = ComplexNumber(x.real / n, x.imag / n);
}
return a;
}
// Polynomial Multiplication using FFT
static std::vector<long long> multiplyPolynomials(
const std::vector<long long>& a,
const std::vector<long long>& b) {
// Find the next power of 2
int n = 1;
while (n < a.size() + b.size())
n <<= 1;
// Convert to complex numbers
std::vector<ComplexNumber> fa(n), fb(n);
for (size_t i = 0; i < a.size(); i++)
fa[i] = ComplexNumber(a[i], 0);
for (size_t i = 0; i < b.size(); i++)
fb[i] = ComplexNumber(b[i], 0);
// Transform both polynomials
fa = transform(fa);
fb = transform(fb);
// Multiply point-wise
for (int i = 0; i < n; i++)
fa[i] = fa[i] * fb[i];
// Inverse transform
fa = transform(fa, true);
// Convert back to integers
std::vector<long long> result(n);
for (int i = 0; i < n; i++)
result[i] = std::round(fa[i].real);
return result;
}
};
// Example usage and demonstration
int main() {
// Complex Number Operations
ComplexNumber a(3, 2); // 3 + 2i
ComplexNumber b(1, -1); // 1 - i
std::cout << "Complex Number Operations:\n";
std::cout << "a = "; a.print(); std::cout << std::endl;
std::cout << "b = "; b.print(); std::cout << std::endl;
ComplexNumber sum = a + b;
ComplexNumber diff = a - b;
ComplexNumber prod = a * b;
std::cout << "Sum (a + b) = "; sum.print(); std::cout << std::endl;
std::cout << "Difference (a - b) = "; diff.print(); std::cout << std::endl;
std::cout << "Product (a * b) = "; prod.print(); std::cout << std::endl;
std::cout << "\nComplex Number Properties:\n";
std::cout << "Magnitude of a: " << a.magnitude() << std::endl;
std::cout << "Argument of a: " << a.argument() << std::endl;
// Polynomial Multiplication Demonstration
std::vector<long long> poly1 = {1, 2, 3}; // 1 + 2x + 3x^2
std::vector<long long> poly2 = {4, 5, 6}; // 4 + 5x + 6x^2
std::cout << "\nPolynomial Multiplication:\n";
std::vector<long long> result = FFT::multiplyPolynomials(poly1, poly2);
std::cout << "Resulting Polynomial Coefficients:\n";
for (size_t i = 0; i < result.size(); i++) {
if (result[i] != 0) {
std::cout << result[i] << "x^" << i;
if (i < result.size() - 1) std::cout << " + ";
}
}
std::cout << std::endl;
return 0;
}# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class TrieNode {
public:
unordered_map<char, TrieNode*> children;
bool isEndOfWord;
TrieNode() : isEndOfWord(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.count(ch) == 0) {
current->children[ch] = new TrieNode();
}
current = current->children[ch];
}
current->isEndOfWord = true;
}
bool search(string word) {
TrieNode* node = findNode(word);
return node && node->isEndOfWord;
}
bool startsWith(string prefix) {
return findNode(prefix) != nullptr;
}
private:
TrieNode* findNode(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.count(ch) == 0) {
return nullptr;
}
current = current->children[ch];
}
return current;
}
}; | String of size n | O(n) | null | <s>[INST]class TrieNode {
public:
unordered_map<char, TrieNode*> children;
bool isEndOfWord;
TrieNode() : isEndOfWord(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.count(ch) == 0) {
current->children[ch] = new TrieNode();
}
current = current->children[ch];
}
current->isEndOfWord = true;
}
bool search(string word) {
TrieNode* node = findNode(word);
return node && node->isEndOfWord;
}
bool startsWith(string prefix) {
return findNode(prefix) != nullptr;
}
private:
TrieNode* findNode(string word) {
TrieNode* current = root;
for (char ch : word) {
if (current->children.count(ch) == 0) {
return nullptr;
}
current = current->children[ch];
}
return current;
}
};# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class FenwickTree {
private:
vector<long long> tree;
int size;
long long getSum(int index) {
long long sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & (-index);
}
return sum;
}
public:
FenwickTree(int n) {
size = n;
tree.resize(n + 1, 0);
}
void update(int index, long long value) {
while (index <= size) {
tree[index] += value;
index += index & (-index);
}
}
long long rangeSum(int left, int right) {
return getSum(right) - getSum(left - 1);
}
}; | Array of size n | O(log n) | null | <s>[INST]class FenwickTree {
private:
vector<long long> tree;
int size;
long long getSum(int index) {
long long sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & (-index);
}
return sum;
}
public:
FenwickTree(int n) {
size = n;
tree.resize(n + 1, 0);
}
void update(int index, long long value) {
while (index <= size) {
tree[index] += value;
index += index & (-index);
}
}
long long rangeSum(int left, int right) {
return getSum(right) - getSum(left - 1);
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class HeavyLightDecomposition {
private:
vector<vector<int>> graph;
vector<int> parent, depth, size, chainHead, chainIndex, position;
int chainCount = 0, currentPos = 0;
SegmentTree* segTree; // Assuming SegmentTree from previous example
void dfs(int node, int par = -1, int d = 0) {
parent[node] = par;
depth[node] = d;
size[node] = 1;
for (int child : graph[node]) {
if (child != par) {
dfs(child, node, d + 1);
size[node] += size[child];
}
}
}
void decompose(int node, int head, int par = -1) {
chainHead[node] = head;
chainIndex[node] = chainCount;
position[node] = currentPos++;
int heavyChild = -1;
int maxSubtreeSize = 0;
for (int child : graph[node]) {
if (child != par && size[child] > maxSubtreeSize) {
heavyChild = child;
maxSubtreeSize = size[child];
}
}
if (heavyChild != -1)
decompose(heavyChild, head, node);
for (int child : graph[node]) {
if (child != par && child != heavyChild) {
chainCount++;
decompose(child, child, node);
}
}
}
public:
HeavyLightDecomposition(vector<vector<int>>& adjacencyList) {
graph = adjacencyList;
int n = graph.size();
parent.resize(n);
depth.resize(n);
size.resize(n);
chainHead.resize(n);
chainIndex.resize(n);
position.resize(n);
dfs(0); // Assuming 0 is the root
decompose(0, 0);
vector<int> values(n); // Replace with actual node values
segTree = new SegmentTree(values);
}
int queryPath(int u, int v) {
int result = INT_MAX;
while (chainIndex[u] != chainIndex[v]) {
if (depth[chainHead[u]] < depth[chainHead[v]])
swap(u, v);
int head = chainHead[u];
result = min(result, segTree->getRangeMinimum(position[head], position[u]));
u = parent[head];
}
if (depth[u] > depth[v])
swap(u, v);
result = min(result, segTree->getRangeMinimum(position[u], position[v]));
return result;
}
}; | array matrix of size n*n | O(log^2(n)) | null | <s>[INST]class HeavyLightDecomposition {
private:
vector<vector<int>> graph;
vector<int> parent, depth, size, chainHead, chainIndex, position;
int chainCount = 0, currentPos = 0;
SegmentTree* segTree; // Assuming SegmentTree from previous example
void dfs(int node, int par = -1, int d = 0) {
parent[node] = par;
depth[node] = d;
size[node] = 1;
for (int child : graph[node]) {
if (child != par) {
dfs(child, node, d + 1);
size[node] += size[child];
}
}
}
void decompose(int node, int head, int par = -1) {
chainHead[node] = head;
chainIndex[node] = chainCount;
position[node] = currentPos++;
int heavyChild = -1;
int maxSubtreeSize = 0;
for (int child : graph[node]) {
if (child != par && size[child] > maxSubtreeSize) {
heavyChild = child;
maxSubtreeSize = size[child];
}
}
if (heavyChild != -1)
decompose(heavyChild, head, node);
for (int child : graph[node]) {
if (child != par && child != heavyChild) {
chainCount++;
decompose(child, child, node);
}
}
}
public:
HeavyLightDecomposition(vector<vector<int>>& adjacencyList) {
graph = adjacencyList;
int n = graph.size();
parent.resize(n);
depth.resize(n);
size.resize(n);
chainHead.resize(n);
chainIndex.resize(n);
position.resize(n);
dfs(0); // Assuming 0 is the root
decompose(0, 0);
vector<int> values(n); // Replace with actual node values
segTree = new SegmentTree(values);
}
int queryPath(int u, int v) {
int result = INT_MAX;
while (chainIndex[u] != chainIndex[v]) {
if (depth[chainHead[u]] < depth[chainHead[v]])
swap(u, v);
int head = chainHead[u];
result = min(result, segTree->getRangeMinimum(position[head], position[u]));
u = parent[head];
}
if (depth[u] > depth[v])
swap(u, v);
result = min(result, segTree->getRangeMinimum(position[u], position[v]));
return result;
}
};# input: array matrix of size n*n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class MinMaxHeap {
private:
vector<int> heap;
bool isMinLevel(int index) {
int level = log2(index + 1);
return level % 2 == 0;
}
void swapIfNeeded(int i, int j) {
if (heap[i] > heap[j]) {
swap(heap[i], heap[j]);
}
}
void bubbleUp(int index) {
if (index == 0) return;
int parentIndex = (index - 1) / 2;
if (isMinLevel(index)) {
if (heap[index] > heap[parentIndex]) {
swap(heap[index], heap[parentIndex]);
bubbleUpMax(parentIndex);
} else {
bubbleUpMin(index);
}
} else {
if (heap[index] < heap[parentIndex]) {
swap(heap[index], heap[parentIndex]);
bubbleUpMin(parentIndex);
} else {
bubbleUpMax(index);
}
}
}
void bubbleUpMin(int index) {
int grandParentIndex = (index - 3) / 4;
while (index > 2 && heap[index] < heap[grandParentIndex]) {
swap(heap[index], heap[grandParentIndex]);
index = grandParentIndex;
grandParentIndex = (index - 3) / 4;
}
}
void bubbleUpMax(int index) {
int grandParentIndex = (index - 3) / 4;
while (index > 2 && heap[index] > heap[grandParentIndex]) {
swap(heap[index], heap[grandParentIndex]);
index = grandParentIndex;
grandParentIndex = (index - 3) / 4;
}
}
public:
void insert(int value) {
heap.push_back(value);
bubbleUp(heap.size() - 1);
}
int getMin() {
if (heap.empty()) throw runtime_error("Heap is empty");
return heap[0];
}
int getMax() {
if (heap.size() == 1) return heap[0];
if (heap.size() == 2) return heap[1];
return max(heap[1], heap[2]);
}
}; | Array of size n | O(log(n)) | null | <s>[INST]class MinMaxHeap {
private:
vector<int> heap;
bool isMinLevel(int index) {
int level = log2(index + 1);
return level % 2 == 0;
}
void swapIfNeeded(int i, int j) {
if (heap[i] > heap[j]) {
swap(heap[i], heap[j]);
}
}
void bubbleUp(int index) {
if (index == 0) return;
int parentIndex = (index - 1) / 2;
if (isMinLevel(index)) {
if (heap[index] > heap[parentIndex]) {
swap(heap[index], heap[parentIndex]);
bubbleUpMax(parentIndex);
} else {
bubbleUpMin(index);
}
} else {
if (heap[index] < heap[parentIndex]) {
swap(heap[index], heap[parentIndex]);
bubbleUpMin(parentIndex);
} else {
bubbleUpMax(index);
}
}
}
void bubbleUpMin(int index) {
int grandParentIndex = (index - 3) / 4;
while (index > 2 && heap[index] < heap[grandParentIndex]) {
swap(heap[index], heap[grandParentIndex]);
index = grandParentIndex;
grandParentIndex = (index - 3) / 4;
}
}
void bubbleUpMax(int index) {
int grandParentIndex = (index - 3) / 4;
while (index > 2 && heap[index] > heap[grandParentIndex]) {
swap(heap[index], heap[grandParentIndex]);
index = grandParentIndex;
grandParentIndex = (index - 3) / 4;
}
}
public:
void insert(int value) {
heap.push_back(value);
bubbleUp(heap.size() - 1);
}
int getMin() {
if (heap.empty()) throw runtime_error("Heap is empty");
return heap[0];
}
int getMax() {
if (heap.size() == 1) return heap[0];
if (heap.size() == 2) return heap[1];
return max(heap[1], heap[2]);
}
};# input: Array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
class SuffixArray {
private:
vector<int> suffixArr;
vector<int> lcp;
string text;
void countingSort(vector<int>& p, vector<int>& c) {
int n = p.size();
vector<int> count(n, 0);
vector<int> newP(n);
for (int x : c)
count[x]++;
vector<int> pos(n);
for (int i = 1; i < n; i++)
pos[i] = pos[i-1] + count[i-1];
for (int x : p) {
int i = c[x];
newP[pos[i]] = x;
pos[i]++;
}
p = newP;
}
public:
SuffixArray(const string& s) : text(s) {
int n = text.length();
vector<pair<char, int>> a(n);
// Initial sorting
for (int i = 0; i < n; i++)
a[i] = {text[i], i};
sort(a.begin(), a.end());
// Initial ranks and suffix array
vector<int> p(n), c(n);
for (int i = 0; i < n; i++)
p[i] = a[i].second;
c[p[0]] = 0;
for (int i = 1; i < n; i++)
c[p[i]] = c[p[i-1]] + (a[i].first != a[i-1].first);
// Sorting suffixes in log(n) iterations
int k = 0;
while ((1 << k) < n) {
for (int i = 0; i < n; i++)
p[i] = (p[i] - (1 << k) + n) % n;
countingSort(p, c);
vector<int> newC(n);
newC[p[0]] = 0;
for (int i = 1; i < n; i++) {
pair<int, int> prev = {c[p[i-1]], c[(p[i-1] + (1 << k)) % n]};
pair<int, int> curr = {c[p[i]], c[(p[i] + (1 << k)) % n]};
newC[p[i]] = newC[p[i-1]] + (prev != curr);
}
c = newC;
k++;
}
suffixArr = p;
computeLCP();
}
void computeLCP() {
int n = text.length();
vector<int> rank(n, 0);
for (int i = 0; i < n; i++)
rank[suffixArr[i]] = i;
lcp.assign(n, 0);
int k = 0;
for (int i = 0; i < n; i++) {
if (rank[i] == n - 1) {
k = 0;
continue;
}
int j = suffixArr[rank[i] + 1];
while (i + k < n && j + k < n && text[i + k] == text[j + k])
k++;
lcp[rank[i]] = k;
k = max(k - 1, 0);
}
}
vector<int> getSuffixArray() {
return suffixArr;
}
vector<int> getLCP() {
return lcp;
}
}; | String of size n | O(n log n) | null | <s>[INST]class SuffixArray {
private:
vector<int> suffixArr;
vector<int> lcp;
string text;
void countingSort(vector<int>& p, vector<int>& c) {
int n = p.size();
vector<int> count(n, 0);
vector<int> newP(n);
for (int x : c)
count[x]++;
vector<int> pos(n);
for (int i = 1; i < n; i++)
pos[i] = pos[i-1] + count[i-1];
for (int x : p) {
int i = c[x];
newP[pos[i]] = x;
pos[i]++;
}
p = newP;
}
public:
SuffixArray(const string& s) : text(s) {
int n = text.length();
vector<pair<char, int>> a(n);
// Initial sorting
for (int i = 0; i < n; i++)
a[i] = {text[i], i};
sort(a.begin(), a.end());
// Initial ranks and suffix array
vector<int> p(n), c(n);
for (int i = 0; i < n; i++)
p[i] = a[i].second;
c[p[0]] = 0;
for (int i = 1; i < n; i++)
c[p[i]] = c[p[i-1]] + (a[i].first != a[i-1].first);
// Sorting suffixes in log(n) iterations
int k = 0;
while ((1 << k) < n) {
for (int i = 0; i < n; i++)
p[i] = (p[i] - (1 << k) + n) % n;
countingSort(p, c);
vector<int> newC(n);
newC[p[0]] = 0;
for (int i = 1; i < n; i++) {
pair<int, int> prev = {c[p[i-1]], c[(p[i-1] + (1 << k)) % n]};
pair<int, int> curr = {c[p[i]], c[(p[i] + (1 << k)) % n]};
newC[p[i]] = newC[p[i-1]] + (prev != curr);
}
c = newC;
k++;
}
suffixArr = p;
computeLCP();
}
void computeLCP() {
int n = text.length();
vector<int> rank(n, 0);
for (int i = 0; i < n; i++)
rank[suffixArr[i]] = i;
lcp.assign(n, 0);
int k = 0;
for (int i = 0; i < n; i++) {
if (rank[i] == n - 1) {
k = 0;
continue;
}
int j = suffixArr[rank[i] + 1];
while (i + k < n && j + k < n && text[i + k] == text[j + k])
k++;
lcp[rank[i]] = k;
k = max(k - 1, 0);
}
}
vector<int> getSuffixArray() {
return suffixArr;
}
vector<int> getLCP() {
return lcp;
}
};# input: String of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
struct TreapNode {
int key, priority;
TreapNode *left, *right;
TreapNode(int k) : key(k), priority(rand()), left(nullptr), right(nullptr) {}
};
class Treap {
private:
TreapNode* root;
TreapNode* rotateRight(TreapNode* y) {
TreapNode* x = y->left;
y->left = x->right;
x->right = y;
return x;
}
TreapNode* rotateLeft(TreapNode* x) {
TreapNode* y = x->right;
x->right = y->left;
y->left = x;
return y;
}
TreapNode* insert(TreapNode* node, int key) {
if (!node) return new TreapNode(key);
if (key <= node->key) {
node->left = insert(node->left, key);
if (node->left->priority > node->priority)
node = rotateRight(node);
} else {
node->right = insert(node->right, key);
if (node->right->priority > node->priority)
node = rotateLeft(node);
}
return node;
}
public:
Treap() : root(nullptr) {}
void insert(int key) {
root = insert(root, key);
}
}; | array of size n | O(log n) | null | <s>[INST]struct TreapNode {
int key, priority;
TreapNode *left, *right;
TreapNode(int k) : key(k), priority(rand()), left(nullptr), right(nullptr) {}
};
class Treap {
private:
TreapNode* root;
TreapNode* rotateRight(TreapNode* y) {
TreapNode* x = y->left;
y->left = x->right;
x->right = y;
return x;
}
TreapNode* rotateLeft(TreapNode* x) {
TreapNode* y = x->right;
x->right = y->left;
y->left = x;
return y;
}
TreapNode* insert(TreapNode* node, int key) {
if (!node) return new TreapNode(key);
if (key <= node->key) {
node->left = insert(node->left, key);
if (node->left->priority > node->priority)
node = rotateRight(node);
} else {
node->right = insert(node->right, key);
if (node->right->priority > node->priority)
node = rotateLeft(node);
}
return node;
}
public:
Treap() : root(nullptr) {}
void insert(int key) {
root = insert(root, key);
}
};# input: array of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
bool isPalindrome(string s, int left, int right) {
if (left >= right) return true;
if (s[left] != s[right]) return false;
return isPalindrome(s, left + 1, right - 1);
}
bool checkPalindrome(string s) {
return isPalindrome(s, 0, s.length() - 1);
} | string of size n | O(n) | null | <s>[INST]bool isPalindrome(string s, int left, int right) {
if (left >= right) return true;
if (s[left] != s[right]) return false;
return isPalindrome(s, left + 1, right - 1);
}
bool checkPalindrome(string s) {
return isPalindrome(s, 0, s.length() - 1);
}# input: string of size n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
} | Integer n | O(sqrt(n)) | null | <s>[INST]bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}# input: Integer n [/INST] This input is to be evaluated for time complexity in BigO notation</s> |
README.md exists but content is empty.
- Downloads last month
- 38