text stringlengths 1 24.5M |
|---|
#include <cstdlib>
#include <iostream>
#include "sort.h"
using namespace std;
using namespace alg;
/////////////////////////////
//
// custom compare function
//
/////////////////////////////
bool comp(int a,int b){
if (a>=b)
return true;
return false;
}
/////////////////////////////
//
// custom swap functi... |
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
using namespace alg;
int main()
{
Stack<int> S(4);
S.push(7);
S.push(5);
S.push(-1);
printf("push return value when has capacity: %d\n",S.push(9));
printf("push return value when full: %d\n",S.push(10));
for (uint32_t i=0; i< S.count();i++) {
printf("... |
#include <iostream>
#include <string>
#include <math.h>
#include "suffix_array.h"
using namespace std;
using namespace alg;
void print(string::iterator b, string::iterator e) {
for(auto it=b;it!=e;++it) cout<<*it;
}
int main()
{
string str;
while(cin>>str) {
SuffixArray sa(str);
cout<<endl;
cout<<"sorted s... |
#include "suffix_tree.h"
#include <iostream>
int SuffixTree::search(string sub)
{
Node* node = &root;
bool in_edge = false; // Are we searching in middle of an edge?
Edge* edge = NULL;
int edge_pos = 0, edge_len = 0;
int result = -1;
for (unsigned int i=0; i<sub.size(); i++) {
char cur = sub[i];
if (in_ed... |
#include "trie.h"
int main(void) {
alg::Trie trie;
const char *strs[] = {"sap", "sat", "sad", "rat", "ram", "rag", "rap", "sat", "ram","rag", "nap", "Nat", "lap"};
for (uint32_t i=0;i<sizeof(strs)/sizeof(char*);i++) {
char * str = strdup(strs[i]);
trie.Add(str);
free(str);
}
printf("count of :%s %d\n", "... |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "undirected_graph.h"
using namespace alg;
int main()
{
srand(time(NULL));
int NVERTEX = 20;
UndirectedGraph * g = UndirectedGraph::randgraph(NVERTEX);
g->printdot();
printf("Random Delete Vertex:\n");
// random delete vertex
int i;
for(i=0;i... |
/*******************************************
* DANIEL'S PRIVATE ALGORITHM IMPLEMENTAIONS
* Universal Hashing
* Features:
* 1. randomized hash function, random a1,a2.. a32
* 2. alloc your storage larger than UHash->prime
* 3. the collsion expectation:
E[Cx] = (n - 1 ) / m (n: number of elements, m: bucket siz... |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "generic.h"
#include "word_seg.h"
using namespace alg;
int main(void)
{
WordSeg ws("./src/dict.txt.sogou");
char buf[1024];
printf("input a sentence in GB18030 encoding, no more than 256 words:\n");
while(1){
scanf("%s", buf);
char *part... |
#ifndef ALGO_BYTEORDER_H__
#define ALGO_BYTEORDER_H__
#include <stdint.h>
#include <stdbool.h>
/**
* test endianness of current machine
* mem: 0D 0C 0B 0A //big endian
* mem: 0A 0B 0C 0D //little endian
* V=0x0D0C0B0A
*/
static inline bool
is_big_endian()
{
int v=0x0D0C0B0A;
char c = *(char*)&v;
if (c == ... |
#ifndef ALGO_GB18030_H__
#define ALGO_GB18030_H__
/**
* Read from the string encoded in GB18030 into WORD
* return the length of the WORD
*/
static inline short
gb18030_read(const char * str, int start, uint32_t * WORD)
{
unsigned char * w = (unsigned char *)&str[start];
if (w[0] <= 0x7F) { // 1-byte
*WORD = ... |
/*
title: all permutation of a string
what will it do: It will generate all permutation of a string
time complexity: O(n*n!)
code written and tested by: https://github.com/rafu01
date: 10-oct-2020
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 1st approach
... |
/*
Language - C++
The Knights Tour Backtracking Problem
Statement - The knight is placed on the first block
of an empty board and, moving according to the rules of chess,
must visit each square exactly once.
Define the size of the chess board in the #define at line 17.
*/
#include <iostream>
using namespac... |
/*
To find a subset of an array whose sum is
equal to a specified number.
Using Backtracking Approach.
Time Complexity: - Worst case O(2^n)
Space Complecity: - O(1)
*/
#include <bits/stdc++.h>
using namespace std;
// BACKTRACKING ALGORITHM
void subsetsum(int Set[], int pos, int sum, int tmpsum, int size, bool & fou... |
#include<bits/stdc++.h>
using namespace std;
//to check if allocation of books among given students is possible.
int isPossible(vector < int > & A, int pages, int students) {
int cnt = 0;
int sumAllocated = 0;
for (int i = 0; i < A.size(); i++) {
if (sumAllocated + A[i] > pages) {
cnt++;
sumAllo... |
#include<bits/stdc++.h>
using namespace std;
int kthelement(int arr1[], int arr2[], int m, int n, int k) {
if(m > n) {
return kthelement(arr2, arr1, n, m, k);
}
int low = max(0,k-m), high = min(k,n);
while(low <= high) {
int cut1 = (low + high) >> 1;
int cut2 ... |
#include<bits/stdc++.h>
using namespace std;
float median(int nums1[],int nums2[],int m,int n) {
int finalArray[n+m];
int i=0,j=0,k=0;
while(i<m && j<n) {
if(nums1[i]<nums2[j]) {
finalArray[k++] = nums1[i++];
}
else {
finalArray[k++] = nums2[j++];
}
... |
#include <bits/stdc++.h>
using namespace std;
double multiply(double number, int n) {
double ans = 1.0;
for(int i = 1;i<=n;i++) {
ans = ans * number;
}
return ans;
}
void getNthRoot(int n, int m) {
double low = 1;
double high = m;
double eps = 1e-7;
while((high - low) > e... |
/* Bleak Number
Given an integer, check whether it is Bleak or not.
A number is called Bleak if it cannot be represented as sum of a positive number 'x' and set bit count in 'x', i.e.,
x + countSetBits(x) is not equal to n for any non-negative number x.
*/
#include <iostream>
using namespace std;
int countSetBits(i... |
/* Swap Two Nibbles
Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits).
The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.
*/
#include <iostream>
using namespace std;
int main()
{
int swapNibbles(int... |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
// For getting pth bit
int getbit(int n,int p){
int mask = (n&(1<<p));
int bit = mask>0?1:0;
return bit;
}
// Setting pth bit
int setbit(int n, int p){
int mask = (n|(1<<p));
return mask;
}
// clr pth bit
void clrbit(int &n, int p){
n = (n&(~(1... |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int dtobint(int n){
int ans= 0,p=1;
while(n>0){
int lsbit = (n&1);
ans+=p*lsbit;
p*=10;
n>>=1;
}
return ans;
}
string dtob(int n){
string a = "";
while(n>0){
if(n&1){
a.append("1");
}else{
a.append("0");
}
n>>=1;
}
revers... |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll replace(ll n,ll m, int i, int j){
int maskclr = (n&(((-1)<<(j+1))|((1<<i)-1)));
int maskshf = m<<i;
return maskshf|maskclr;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll n = 15;
ll m = 2;
int i=1,j=3... |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int counter =0;
void generator(string s,int n){
counter++;
int j = 0;
while(n>0){
int lsb = (n&1);
if(lsb){
cout<<s[j];
}
j++;
n>>=1;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin... |
/*problem statement:Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8)
and one empty space. The objective is to place the numbers on tiles to match final configuration
using the empty space. We can slide four adjacent (left, right, above and below) tiles into the
empty space.*/
// Program to prin... |
/*
Title:Tiling Problem using Divide and Conquer algorithm.
Description: Given a n x n board where n is of form 2^k where k >= 1.The board has one missing cell (of size 1 x 1).
Expected Result: To fill the board using L shaped tiles of size(2x2) with one cell of size 1×1 missing.
*/
#include <bits/stdc++.h>
using na... |
// Kadane's Algorithm
// Algorithm for finding the max subarray sum in O(n)
#include <bits/stdc++.h>
using namespace std;
int max_subarray_sum(int A[], int n) {
int ans = INT_MIN; // It can be set to 0 if an empty array is allowed as solution
int sum = 0;
for (int i = 0; i < n; i++) {
sum += A[i... |
/*
Title - Knapsack Problem solution in C++
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
Remember you can only take an items atmost once.
INPUT FORMAT
------------
First line will have n and W the number of items, and the maximum... |
//Dynamic Programming approach to the longest common subsequence
//Dynamic programming approach to the longest common subsequence
#include<bits/stdc++.h>
using namespace std;
int lcs(string X,string Y,int n,int m)
{
//Initializing the two dimensional table
int t[m+1][n+1];
for(int i=0;i<m+1;i++)
{
... |
//C++
//Implement the longest Common subsequence of three sequences in C++
#include<bits/stdc++.h>
using namespace std;
int lcs(int X[],int Y[],int Z[],int n,int m,int o)
{
int t[n+1][m+1][o+1];
for(int i=0;i<n+1;i++)
{
for(int j=0;j<m+1;j++)
{
for(int k=0;k<o+1;k++)
... |
/*
Title - Longest Increasing Subsequence.
Given an array it will find the length of the longest subsequence in that array
which is strictly increasing.
This algo can be modified to stor that same subsequence.
This algorithm uses Dynamic Programming to find the LIS.
Complexity - O(n*n)
*/
#include<bits/stdc++.h>
us... |
// Title - Longest Palindromic Subsequence
// Statement - It will find the length of the Longest Palindromic Subsequence in a string
// Time complexity - O(n^2)
#include<bits/stdc++.h>
using namespace std;
// Returns the length of the longest palindromic subsequence in given string
int lps(string &str)
{
int ... |
#include<bits/stdc++.h>
using namespace std;
int adjacent(vector<vector<int> > &A) {
int n=A[0].size();
if(n==0)
return -1;
vector<int> dp(n,0);
dp[0]=max(A[0][0],A[1][0]);
if(n==1)
return dp[0];
dp[1]=max(A[0][1],A[1][1]);
for(int i=2;i<n;i++)//For each index
{
dp[i... |
#include<bits/stdc++.h>
using namespace std;
int func(int arr[], int n , int v){
int dp[v+1];
dp[0] = 0;
for(int i=1; i<=v; i++){
dp[i] = INT_MAX;
}
for(int i=1; i<=v; i++){
for(int j=0; j<n ; j++){
if(arr[j]<=i && dp[i-arr[j]] != INT_MAX){
dp[i... |
/*Finds minimum cost path in a matrix traversal
staring from(0,0) to (n-1,n-1)
After finding the minimum cost it traces the path of
minimum cost traversal*/
#include<bits/stdc++.h>
using namespace std;
int min(int a,int b,int c){
return (a<b && a<c )? a: b<c ? b: c ;
}
int main(){
int n,m;
cin>>n>>m;
int arr[n]... |
// Dynamic Programming Optimized Solution for Palindrome Partitioning Problem
/*Given a string, a partitioning of the string is a palindrome partitioning if every substring of the partition is a palindrome.
For example, “aba|b|bbabb|a|b|aba†is a palindrome partitioning of “ababbbabbababaâ€.
Determine the fewe... |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; //n represents the nth stair where a person wants to go
cin>>n;
int i;
vector<int>A(n+1,0);
A[0]=1;
for(i=1;i<=n;i++)
{
A[i]+=A[i-1]; //number of ways from the previous step
if(i>1)
A[i]+=A[i-2]; // nu... |
// Dynamic Programming Solution Optimized for Subset Sum Count
// Example and Description: A set of positive integers is given (i.e. {1, 2, 4}) as well as a sum (i.e. 3).
// Return a boolean evaluated based on if there exists a subset (i.e. {1, 2}), or not, of
// the given set that adds up to the provided sum. The exa... |
#include <iostream>
#include <map>
using namespace std;
class Node
{
public:
int data;
Node *next;
// constructor
Node(int data)
{
this->data = data;
this->next = NULL;
}
// destructor
~Node()
{
int value = this->data;
// memory free
if (th... |
/*
Kosaraju Algorithm -
Given a directed graph, the
algorithm computes all the
strongly connected components
Time Complexity - O(V + E)
*/
#include <bits/stdc++.h>
using namespace std;
// declaring global variables
vector<vector<int>> edges, edgesT;
vector<bool> visited;
stack<int> s;
int n, e;
... |
You are given array prices [] which contain the price of a stock on some days. You have to choose one day for buying the stock and a different one for selling it. Return the days on which you buy and sell the stock.
//author - Sushrut Shukla
#include
#include<bits/stdc++.h>
using namespace std;
int main() {
... |
#include <iostream>
using namespace std;
int miniDist(int distance[], bool Tset[],int m,int n) // finding minimum distance
{
int minimum=INT_MAX,ind;
for(int k=0;k<m;k++)
{
if(Tset[k]==false && distance[k]<=minimum)
{
minimum=distance[k];
ind=k;
}
}
... |
/*
title: Kruskal algorithm to find minimum spanning tree of a graph
what will it do: It will find the minimum spanning tree of a graph
time complexity: O(ElogE) --> E = edges (Edge based algorithm)
code written and tested by: https://github.com/rafu01
date: 3-oct-2020
*/
#include <bits/stdc++.h>
... |
/*
title: Prims algorithm to find minimum spanning tree of a graph
what will it do: It will find the minimum spanning tree of a graph
time complexity: O(VlogE) --> V= vertices, E = edges (Vertices based algorithm)
code written and tested by: https://github.com/rafu01
date: 3-oct-2020
*/
#include <... |
/*
Find the maximum product of two distinct numbers in a sequence of non-negative integers
Input: A sequence of non-negative integers
Output: The maximum value that can be obtained by multiplying two different elements from the sequence.
Input format. The first line contains an integer n. The next line ... |
#include <iostream>
using namespace std;
#define M 1000000007
//Binary exponentiation
//Calculating a^n in O(log n) time complexity
// int power(int a,int n)
// {
// int res=1;
// while(n>0)
// {
// if(n&1) //if n is odd
// {
// res = res*a;
// }
// a = a*a; ... |
/*
Z Algorithm:
Given a pattern and text, this
algorithm computes all the locations
where pattern is present
Time Complexity - O(n + m)
*/
#include <iostream>
using namespace std;
/* Z of i finds the length of
longest substring that is also
a prefix starting from i
*/
int *zFunction(str... |
#include <bits/stdc++.h>
using namespace std;
/*
Centroid of a Tree is a node which if removed from the tree would split it into a ‘forest’,
such that any tree in the forest would have at most half the number of vertices in the original tree.
We use dfs algorithm to easily calculate the centroid of a tree.
A tree ... |
/*Extended Euclid's GCD
An algorithm to compute integers x and y such that
ax + by = gcd(a,b) for given a and b.
*/
#include <iostream>
using namespace std;
int gcd(int a, int b, int &x, int &y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
int x1, y1;
int d = gcd(b % a, a, x1,... |
#include <iostream>
using namespace std;
// Recursive function to return Fibonacci List
int fibonacciList(int n)
{
// Checks if n<=1, i.e. 0 and 1
if (n <= 1)
{
return n;
}
else
{
// Returns the function recursively for the next number
return fibonacciList(n - 1) + fibon... |
#include <iostream>
using namespace std;
void factors(int n, int i)
{
// Checking if the number is less than n
if (i <= n)
{
if (n % i == 0)
{
cout << i << " ";
}
// Calling the function recursively for the next number
factors(n, i + 1);
}
}
int main... |
#include <iostream>
using namespace std;
int fibonacciNumber(int n){
// Checks if n<=1, i.e. 0 and 1
if(n<=1) {
return n;
}
else {
// Returns the function recursively for the next number
return fibonacciNumber(n - 1) + fibonacciNumber(n - 2);
}
}
int main() {
/*
... |
// C++ program to calculate pow(a,b)
#include <iostream>
using namespace std;
int power(int a, int b)
{
//base case
if (b == 0)
return 1;
//recursive cases
if (b % 2 == 0) //b is even
{
return power(a, b / 2) * power(a, b / 2);
}
else //b is odd
{
return a * power(a, b / 2) * power(a, b / 2);
}
}
int... |
/*
Title - Recusive Factorial
Description- A Program to recursively calculate factorial of a positive integer.
Note- This allows to calculate factorials of numbers upto 20. After 20, the factorial
value will exceed the capacity of largest positive integer data type [unsigned long long].
*/
#include<bits/stdc++.h>
u... |
/*
Title - Recusive Sum
Description- A Program to recursively calculate sum of N natural numbers.
*/
#include<bits/stdc++.h>
using namespace std;
// A recursive function to calculate the sum of N natural numbers
int recursiveSum(int num)
{
if(num == 0)
return 0;
return (recursiveSum(num - 1) + num); ... |
//Problem-Tower of Hanoi
// Tower of hanoi is a problem in which we have 3 rods and n disks.
// The objective of the problem is to move the entire stack to another rod, by following the below rules:-
// 1)Only one disk can be moved at a time.
// 2)Each move consists of taking the upper disk from one of the stacks and p... |
/* ë°”ì´ë„ˆë¦¬ 서치 ì•Œê³ ë¦¬ì¦˜ cpp */
// Binary search algorithm
// This algorithm finds the index of an element in a sorted array
// Time complexity : O(log n)
// Space complexity :
// 1. Recursive approach : O(log n)
// 2. Iterative approach : O(1)
#include <iostream>
#include <vector>
using namespace... |
/*
finding the element ele using exponential search
*/
#include <bits/stdc++.h>
using namespace std;
int binary_search(int arr[], int, int, int);
//exponential search - returns the position of first occurrence of ele in array
int exponential_search(int arr[], int size, int ele)
{
//If ele is present at arr[0]
... |
// C++ program to implement interpolation search
#include<bits/stdc++.h>
using namespace std;
Â
// If x is present in arr[0..n-1], then returns
// index of it, else returns -1.
int interpolationSearch(int arr[], int n, int x)
{
    // Find indexes of two corners
    int lo = 0, hi = (n - 1);
Â
    // Sinc... |
#include<iostream>
using namespace std;
bool search(int arr[], int size, int key){
for(int i=0; i<size; i++){
if(arr[i]==key){
return 1;
}
}
return 0;
}
int main()
{
int arr[10]={5,7,-2,10,22,-2,0,5,22,1};
//whether 1 is present in it or not
cout<<"Enter the el... |
//A string matching algorithm which can find a string in a given text
//Worst case Time complexity - O(mn) where n is the length of text and m is the length of string to be found
#include<bits/stdc++.h>
using namespace std;
int rabinKarp(string txt, string pat, int q)
{
int txt_len = txt.length();
int pat_len =... |
/*
Sieve of Eratosthenes:
Given a number n, print all prime numbers less than n
*/
#include <iostream>
using namespace std;
void sieve_of_eratosthenes(int n)
{
/*
This will print all
prime number less than n
*/
// Initially all are prime
bool *prime = new bool[n];
for (int i = 0;... |
/*
Algorithm: Sieve of Sundaram.
Given a number n, print all prime numbers less than n
*/
#include <bits/stdc++.h>
using namespace std;
int sieve_of_sundaram(int n)
{
// Sieve of Sundaram produces primes smaller than (2*x + 2) for a number given number x.
int m = (n-1)/2;
// This array... |
#include <iostream>
using namespace std;
void bubbleSort(int array[], int size) {
/* run loops two times
* one for walking through the array
* and the other for comparison
*/
for(int step=0;step-size-1;step++){
bool swapped = false;
for(int i=0;i<size-step-1;i++) {
... |
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Implements the counting sort algorithm on an input array of integers.
*
* @param array - An array of integers to be sorted.
*
* @return An array of integers sorted in non-descending order.
*
* Time Complexity:
* - O(n + k), ... |
/* For heap sort we first create a max heap of the data.
We know that the root of the heap is largest. The root is
replaced with the last node and then removed.
We again heapify the root and this process is continued. */
/* Time Complexity : O(nlogn) */
#include <iostream>
using namespace std;
#define MAX 1... |
#include <bits/stdc++.h>
using namespace std;
/*
Function to sort an array using Insertion Sort;
Time Complexity : O(n*n);
Space Complexity : O(1);
*/
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int k = arr[i];
int j = i - 1;
while (j >= 0 and k < arr[j]) {
arr[j + 1] = ... |
/* Merge Sort is is a Divide and Conquer algorithm.
The array is recursively divided the array in two halves till the size becomes 1.
Then the array is merged in arranged order. */
/* Time complexity : O(nlogn) in all cases
Space complexity: O(n) */
#include <bits/stdc++.h>
using namespace std;
#define MAX ... |
/*
* Pigeonhole sort is a non-comparison sorting algorithm that is useful when sorting integers.
*
* time complexity: O(N + n) for all cases
* n = number of elements in array
* N = the range of possible values with array to be sorted
*
* pigeonhole sort is suitable for whenever N and n are approximately the same.
*/
#i... |
/* Quick Sort is Divide and Conquer algorithm for sorting data.
In this algorithm we pick an element (in this case last element) as pivot
and partitions the array around the pivot such that LHS of pivot is less
than the pivot and RHS of pivot is greater than the pivot.*/
/* Time complexity: Worst case : O(n^... |
/*
* Selection Sort Implementation in C++
*/
#include <bits/stdc++.h>
using namespace std;
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, minIndex;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1... |
/*
Short Introduction:-
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.
This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right
and has to be moved to the far left.This algorithm uses insertion sort on a widely spread elemen... |
#include<bits/stdc++.h>
using namespace std;
class TrieNode{
public:
bool is_end;
vector<TrieNode*> children;
TrieNode(){
is_end=false;
children=vector<TrieNode*>(26, NULL);
}
};
class Trie{
public:
TrieNode* getRoot(){return root;}
Trie(vector<string>& words){
root=n... |
#include<bits/stdc++.h>
using namespace std;
bool check(int node, int color[], bool graph[101][101], int n, int col) {
for (int k = 0; k < n; k++) {
if (k != node && graph[k][node] == 1 && color[k] == col) {
return false;
}
}
return true;
}
bool solve(int node, int color[], int m, int N, bool graph... |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool check(int row, int col, vector < string > board, int n) {
// check upper element
int duprow = row;
int dupcol = col;
while (row >= 0 && col >= 0) {
if (board[row][col] == 'Q')
return false;
... |
#include<bits/stdc++.h>
using namespace std;
int n;
int queen[20]; // to store the ith queen pos (ith queen pos => col num in which its saved)
bool check(int row,int col){
// here we have to check from 0 to row whether any queen(queen[row]) can attk the cur level
for(int i=0;i<row;i++){
int pre_row=i;... |
#include <bits/stdc++.h>
using namespace std;
class Solution {
void findPathHelper(int i, int j, vector < vector < int >> & a, int n, vector < string > & ans, string move,
vector < vector < int >> & vis) {
if (i == n - 1 && j == n - 1) {
ans.push_back(move);
return;
}
// downward
if... |
#include<bits/stdc++.h>
using namespace std;
bool isValid(vector < vector < char >> & board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][col] == c)
return false;
if (board[row][i] == c)
return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)
... |
/* Question-:given 2 strings s1 and s2.We have to match string s1 containing (*,?,characters)
to string s2 containing only characters,*/
// * can contain characters ranging from 0 to size of string
// ? can contain single string
#include<bits/stdc++.h>
using namespace std;
//Done with the help of recursion
bool fun... |
#include <iostream>
using namespace std;
int foo [5] = {10, 8, 6, 4, 2};
void sum() {
// it print sum of all elements
int i, result = 0;
for(i=0;i<5;i++) {
result += foo[i];
}
cout << "Total sum of array : " << result << endl;
}
void updation() {
// updation of array
foo[1] =... |
// A C++ program to demonstrate working of sort(),
// reverse()
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric> //For accumulate operation
using namespace std;
int main()
{
// Initializing vector with array values
int arr[] = {10, 20, 5, 23 ,42 , 15};
int n = sizeof(arr)/siz... |
// C++ program for count() and find()
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
// initialzing vector with array values
int arr[] = {40, 60, 20, 90, 40, 50, 90};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n);
// count of el... |
// lower bound and upper bound in vectors
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// initialize vectors
int arr[] = {40, 30, 80, 50, 90, 20, 30, 100};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect(arr, arr+n);
// sort array to make s... |
// C++ program erase()
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {5, 11, 15, 20, 25, 30, 35, 40, 5, 10, 15, 20, 25};
int n = sizeof(arr)/sizeof(arr[0]);
vector<int> vect (arr, arr+n);
// print vector
cout << "Print vector : ";
... |
/*
* distance(first_iterator, desired_position) : It returns the distance of desired position from
* the first iterator.
* This function us very useful while finding the index.
*/
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
// initialize vector with... |
#include<bits/stdc++.h>
using namespace std;
void nextPermutation(vector<int>& nums) {
int n = nums.size(), k, l;
for (k = n - 2; k >= 0; k--) {
if (nums[k] < nums[k + 1]) {
break;
}
}
if (k < 0) {
reverse(nums.begin(), nums.end());
} e... |
#include<bits/stdc++.h>
using namespace std;
void setZeroes(vector < vector < int >> & matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][... |
#include <iostream>
using namespace std;
/*
Disjoint Set Union is extremely useful if we want to know the number of components in a graph, size of each components and
whether 2 vertices are in same component or not in almost O(1) time. Disjoint is also useful for detecting cycles in the graph.
Each component is repres... |
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
// finding nod1->par equaility with nod2->par;
// to check whether their same component or not;
// if they are same locality then we count both as 1,
// else both are unique
void dsu(int x,int y,vector<int>&par){
int p1=f... |
// C++ implementation of Topological Sorting
/*
Topological sorting of vertices/nodes of a Directed Acyclic Graph is an linear
ordering of the vertices/nodes v1,v2,v3.... in such a way, that if there is an edge
directed towards vertex/node vj from vertex vi, then vi comes before vj.
*/
#include<bits/stdc++.h>
usi... |
// Graph Representation with Adjaency list
#include<bits/stdc++.h>
using namespace std;
class Graph{
int v;
// Array of list
list<int> *l;
public:
Graph(int v){ //constructor
this->v = v;
l = new list<int>[v];
}
void addEdge(int x, int y)... |
// Graph representation using hash maps(Adjacency list)
// used for both directed and undirected graphs
#include<iostream>
#include<unordered_map>
#include<list>
using namespace std;
class Graph{
unordered_map<string, list<pair<string, int>>> umap;
public:
// x and y are nodes, they can be of any dat... |
// BFS
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
#define fi first
#define se second
using namespace std;
class Graph{
private:
map<int, vector<int> > m;
int size;
public:
Graph(int size){
this->size = size;
}
// adding edges to the graph, f... |
// DFS
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
#define fi first
#define se second
using namespace std;
class Graph{
private:
map<int, vector<int> > m;
vector<bool> visited(1000000, false);
public:
// add Edges to the graph, to get an undirected graph
... |
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <climits>
using std::cout;
using std::endl;
using std::vector;
using std::unordered_map;
using std::unordered_set;
class Graph {
int size;
unordered_map<int, u... |
// **OBSERVATIONS**
// 1. Given that we can **jump to the previous and next neighbour if they are within the limits** from the current position.
// 2. We can also **jump to the same element which is present in the array but at different index** .
// Atlast we have to return the **minimum number of steps to reach the ... |
/*
Finding Articulation Points and bridges using Tarjan's Algorithm.
DFS Tree: Tree formed as a result of DFS while not visiting
the already visited nodes
Backedge: Edge that points to already visited nodes
Discovery Time: First time, a node was visited.
Lowest time(n) = min(backedge from n,
backedge from any... |
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
// constructor
Node(int data)
{
this -> data = data;
this -> next = NULL;
}
~Node()
{
int value = this -> data;
while(this -> next != NULL)
{
del... |
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* previous;
Node* next;
// constructor
Node(int data)
{
this -> data = data;
this -> previous = NULL;
this -> next = NULL;
}
~Node()
{
int value = this -> data;
... |
/*
* Linked List implentation in C++
*/
#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
class Linked_list {
private:
node *head, *tail;
unsigned int size;
public:
Linked_list() {
head = NULL;
tail = NULL;
... |
#include <bits/stdc++.h>
using namespace std;
class LRUCache{
public:
map<int, int> mymap;
list<int> ls;
int cp;
LRUCache(int capacity){
cp=capacity;
mymap.clear();
ls.clear();
}
int get(int key){
if(mymap.find(key)==mymap.end()) return 0;
ls.remove(key);
ls.push_fron... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.