no image
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Our First Contest, and it was a huge success. Thank you for participating. 

Here are the editorial of the problems..


1. Simple Sum 4

Easiest in the Problem set.. and Almost everyone solved it.

Here is my solution code..

 #include <iostream>  
 #include <stdio.h>  
 using namespace std;  
 int main()  
 {  
   int n;  
   while ( scanf("%d",&n) != EOF )  
   {  
     for( int i = 0 ; i < n ; i++)  
     {  
       int x ,y;  
       scanf("%d %d",&x,&y);  
       printf("%d\n",x+y);  
     }  
   }  
   return 0;  
 }  


2 . Kazi And Quadrangles 

Summary : Given 4 lengths, you are to determine if these can form a square, rectangle, quadrangle or none of these.

Explanation :
Easiest way is to sort the array of lengths then check the following:
  • Square: all 4 sides are equal.
  • Rectangle: each 2 sides are equal.
  • Quadrangle: maximum of these lengths must be less than the sum of other 3.
  • None: if none of the above conditions is satisfied, then print "None".
 // Accepted  
 #include <algorithm>  
 #include <cstdio>  
 using namespace std;  
 int len[4];  
 int main(void){  
      int i, t;  
      scanf("%d", &t);  
      while (t--){  
           int s = 0;  
           for (i = 0; i < 4; i++){  
                scanf("%d", &len[i]);  
                s += len[i];  
           }  
           sort(len, len+4);  
           if (len[0] == len[1] && len[2] == len[3]){  
                if (len[1] == len[2])  
                     printf("square\n");  
                else  
                     printf("rectangle\n");  
           } else {  
                bool works = true;  
                for (i = 0; i < 4; i++)  
                     works &= s - len[i] > len[i];  
                if (works)  
                     printf("quadrangle\n");  
                else  
                     printf("None\n");  
           }  
      }  
 }  


3. Pooja And Java

In this problem you should answer to 4 questions:
1)       Can we use type byte to store N?
2)       Can we use type short to store N?
3)       Can we use type int to store N?
4)       Can we use type long to store N?
We should check these conditions in the given order. If all these conditions are wrong, the answer is BigInteger.
The simplest way to check these conditions is to store numbers as strings and write a function to compare such strings. In Java you can use type BigInteger.

 #include <iostream>  
 #include <string>  
 using namespace std;  
 int main()  
 {  
   string s;  
   cin >> s;  
   if(s.size() < 3 || (s.size() == 3 && s <= "127"))  
     cout <<"byte";  
   else if (s.size() < 5 || (s.size() == 5 && s <= "32767"))  
     cout <<"short";  
   else if(s.size() < 10 || (s.size() == 10 && s <= "2147483647"))  
     cout <<"int";  
   else if(s.size() < 19 || (s.size() == 19 && s <= "9223372036854775807"))  
     cout <<"long";  
   else cout <<"BigInteger";  
 }  


4. Fibonacci Revisited

In this problem you need to calculate two fibonacci number which are greater and smaller then given number.
So minimum steps required is min(greater-N,N-smaller); 


 #include<iostream>  
 using namespace std;  
 int find(int N) {  
    int a = 0, b = 1;  
    while(b < N) {  
     int c = a+b;  
     a = b;  
     b = c;  
    }  
    return min(N-a, b-N);  
   }  
 }  
 int main() {  
   long long N;  
   cin>>N;  
  cout <<find(N) << endl;  
  return 0;  
 }  

5. Primorial Numbers

It was challenge Problem Toughest in the given Problem set.
I'll write detailed explanation in free time..
Here is my solution.. try to under the code :D

 #include<cstdio>  
 #include<algorithm>  
 #include<cstring>  
 using namespace std;  
 const int maxn=200000+10;  
 char st[maxn];  
 int res[maxn];  
 int need[maxn];  
 int n;  
 int main()  
 {  
     scanf("%s",st+1);  
     n=strlen(st+1);  
     for (int i=n;i;i--)  
     if (st[i]<'4') need[i]=0;else  
     if (st[i]=='4') need[i]=min(1,need[i+1]);else  
     if (st[i]<'7') need[i]=1;else  
     if (st[i]=='7') need[i]=need[i+1]+1;  
     else need[i]=1000000000;  
     if (n%2==0)  
     {  
         bool ok=1;  
         int a=0,b=0,c=4,flag=0;  
         for (int i=1;i<=n;i++)  
         if (flag)  
         {  
             if (a+1<=n/2) res[i]=4,a++;  
             else res[i]=7,b++;  
         } else  
         {  
             if (st[i]<'4' && a+1<=n/2) res[i]=4,a++,flag=1;else  
             if (st[i]=='4' && a+1<=n/2 && need[i+1]<=n/2-b)res[i]=4,a++;else  
             if (st[i]<'7' && b+1<=n/2) res[i]=7,b++,flag=1;else  
             if (st[i]=='7' && b+1<=n/2) res[i]=7,b++;  
             else ok=0;  
         }  
         if (ok)  
         {  
             for (int i=1;i<=n;i++) printf("%d",res[i]);  
             printf("\n");  
             return 0;  
         }  
         n+=2;  
     } else n+=1;  
     for (int i=1;i<=n/2;i++) printf("4");  
     for (int i=1;i<=n/2;i++) printf("7");  
     printf("\n");  
 }  

Thank you so much friends for participating in the contest. I hope you enjoyed. Our next Contest will be more competitive and Problems will be tricky and Tough. 

Keep Practicing Till then. 
Happy Coding! 
:D 

no image
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Hi there!  This webpage covers the space and time Big-O complexities of common algorithms used in Computer Science.  When preparing for technical interviews in the past, I found myself spending hours crawling the internet putting together the best, average, and worst case complexities for search and sorting algorithms so that I wouldn't be stumped when asked about them. Each time that I prepared for an interview, I thought to myself "Why oh why hasn't someone created a nice Big-O cheat sheet?".  So, to save all of you fine folks a ton of time, I went ahead and created one.  Enjoy

Searching



Algorithm Data Structure Time Complexity Space Complexity


Average Worst Worst
Depth First Search (DFS) Graph of |V| vertices and |E| edges - O(|E| + |V|) O(|V|)
Breadth First Search (BFS) Graph of |V| vertices and |E| edges - O(|E| + |V|) O(|V|)
Binary search Sorted array of n elements     O(log(n)) O(log(n)) O(1)
Linear (Brute Force) Array      O(n) O(n) O(1)
Shortest path by Dijkstra,
using a Min-heap as priority queue
Graph with |V| vertices and |E| edges     O((|V| + |E|) log |V|) O((|V| + |E|)log |V|) O(|V|)
Shortest path by Dijkstra,
using an unsorted array as priority queue
Graph with |V| vertices and |E| edges    O(|V|^2) O(|V|^2) O(|V|)
Shortest path by Bellman-Ford Graph with |V| vertices and |E| edges    O(|V||E|) O(|V||E|) O(|V|)




Sorting



Algorithm Data Structure Time Complexity Worst Case Auxiliary Space Complexity


Best Average Worst Worst
Quicksort Array O(n log(n)) O(n log(n)) O(n^2)              O(n)
Mergesort Array O(n log(n)) O(n log(n)) O(n log(n))              O(n)
Heapsort Array O(n log(n)) O(n log(n)) O(n log(n))              O(1)
Bubble Sort Array O(n) O(n^2) O(n^2)               O(1)
Insertion Sort Array O(n) O(n^2) O(n^2)              O(1)
Select Sort Array O(n^2) O(n^2) O(n^2)              O(1)
Bucket Sort Array O(n+k) O(n+k) O(n^2)              O(nk)
Radix Sort Array O(nk) O(nk) O(nk)              O(n+k)


Data Structures



Data Structure Time Complexity Space Complexity

Average Worst Worst

Indexing Search Insertion Deletion Indexing Search Insertion Deletion
Basic Array O(1) O(n) - - O(1) O(n) - - O(n)
Dynamic Array O(1) O(n) O(n) O(n) O(1) O(n) O(n) O(n) O(n)
Singly-Linked List O(n) O(n) O(1) O(1) O(n) O(n) O(1) O(1) O(n)
Doubly-Linked List O(n) O(n) O(1) O(1) O(n) O(n) O(1) O(1) O(n)
Skip List O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(n) O(n) O(n) O(n) O(n log(n))
Hash Table - O(1) O(1) O(1) - O(n) O(n) O(n) O(n)
Binary Search Tree O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(n) O(n) O(n) O(n) O(n)
Cartresian Tree - O(log(n)) O(log(n)) O(log(n)) - O(n) O(n) O(n) O(n)
B-Tree O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(n)
Red-Black Tree O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(n)
Splay Tree - O(log(n)) O(log(n)) O(log(n)) - O(log(n)) O(log(n)) O(log(n)) O(n)
AVL Tree O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(n)


Heaps


Heaps Time Complexity

Heapify Find Max Extract Max Increase Key Insert Delete Merge
Linked List (sorted) - O(1) O(1) O(n) O(n) O(1) O(m+n)
Linked List (unsorted) - O(n) O(n) O(1) O(1) O(1) O(1)
Binary Heap  O(n) O(1) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(m+n)
Binomial Heap - O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n)) O(log(n))
Fibonacci Heap - O(1) O(log(n))* O(1)* O(1) O(log(n))* O(1)


Graphs

Node / Edge Management Storage Add Vertex Add Edge Remove Vertex Remove Edge Query
Adjacency list O(|V|+|E|) O(1) O(1) O(|V| + |E|) O(|E|) O(|V|)
Incidence list O(|V|+|E|) O(1) O(1) O(|E|) O(|E|) O(|E|)
Adjacency matrix O(|V|^2) O(|V|^2) O(1) O(|V|^2) O(1) O(1)
Incidence matrix O(|V| ⋅ |E|) O(|V| ⋅ |E|) O(|V| ⋅ |E|) O(|V| ⋅ |E|) O(|V| ⋅ |E|) O(|E|)


Notation for asymptotic growth

letter  bound   growth
(theta) Θ                             upper and lower, tight                                      equal
(big-oh) O upper, tightness unknown less than or equal
(small-oh) o upper, not tight less than
(big omega) Ω lower, tightness unknown greater than or equal
(small omega) ω lower, not tight greater than

[1]  Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound). For example, an algorithm taking Omega(n log n) takes at least n log n time but has no upper limit. An algorithm taking Theta(n log n) is far preferential since it takes AT LEAST n log n (Omega n log n) and NO MORE THAN n log n (Big O n log n). SO

[2]  f(x)=Θ(g(n)) means f (the running time of the algorithm) grows exactly like g when n (input size) gets larger. In other words, the growth rate of f(x) is asymptotically proportional to g(n).

[3]  Same thing. Here the growth rate is no faster than g(n). big-oh is the most useful because represents the worst-case behavior.
In short, if algorithm is __ then its performance is __ 

algorithm performance
o(n) < n
O(n) ≤ n
Θ(n) = n
Ω(n) ≥ n
ω(n) > n

Will edit this post soon to make it more easily readable...

Blog Post Credits - Pawan Tiwari(Microsoft SDET US)
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Hello friends, today I'm going to talk about factorial of Negative Numbers.

In mathematics, factorial of a positive Integer say n is given as 

where '*' is multiplication sign.

you know 0! is taken as 1.
Factorial Image

Factorial of a positive integers have great applications in Programming and mathematics. Permutations and combinations is one (where we find the number of ways a group of objects can be arranged or selected in given group of objects). Expansion of terms like (a+b)^n (binomial theorem) are computed using factorials.

We'll discuss about how to find factorials of very large numbers like say 100! or 1000! in programming in my upcoming posts.

Well, let's discuss about factorials about negative numbers here...
 
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Hello Friends, I'm gonna about Graph Theory in my upcoming posts, so here are some basic Graph terminology which will form a base to understand Graph Theory and Algorithms.

 

Overview

  • Definitions: Vertices, edges, paths, etc
  • Representations: Adjacency list and adjacency matrix



Definitions: Graph, Vertices, Edges

  • Define a graph G = (V, E) by defining a pair of sets:
    1. V = a set of vertices
    2. E = a set of edges

  • Edges:
    • Each edge is defined by a pair of vertices
    • An edge connects the vertices that define it
    • In some cases, the vertices can be the same

  • Vertices:
    • Vertices also called nodes
    • Denote vertices with labels

  • Representation:
    • Represent vertices with circles, perhaps containing a label
    • Represent edges with lines between circles

  • Example:
    • V = {A,B,C,D}
    • E = {(A,B),(A,C),(A,D),(B,D),(C,D)}




Motivation

  • Many algorithms use a graph representation to represent data or the problem to be solved

  • Examples:
    • Cities with distances between
    • Roads with distances between intersection points
    • Course prerequisites
    • Network
    • Social networks
    • Program call graph and variable dependency graph

no image
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
  • C++ I/O. Note: Be very careful when you use getline after using cin! The first getline may return an empty line (why?) 
  • Another I/O tutorial by Yury Kholondyrev (warmingup).
  • C++ STL (vectors, lists, sets, maps, pairs) and algorithms. Part 1, Part 2, and Part 3.
  • Graph algorithms (BFS, colored DFS, shotest paths, union/find, spanning trees, Euler paths, flow and matching). Part 1, Part 2, Part 3, Part 4, and Part 5.
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Someone asked me to answer this question on Quora, and I got 200+ upvotes. So, I thought I should share this here on my blog also.

CLRS image


Well, you should read this book from Start to end (From Basics to Masters).

Here are my suggestion on How to read this Book.

Reading and Understanding CLRS:

1. Use video lectures to understand the concept, and read the chapter from the book.
Best site for CLRS lecture videos :
Lecture 1: Administrivia, Introduction, Analysis of Algorithms, Insertion Sort, Mergesort

Video Lectures | Introduction to Algorithms (SMA 5503) | Electrical Engineering and Computer Science | MIT OpenCourseWare
no image
A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
Hello friends, Today I'm sharing some contest templates created by World Class Coders, I will add some more and I'm creating one for C++ as well. You should use this during competitions it will really help and increase your speed, you don't have to type too much..

For C++...

Created by Zobayer

 #include <cassert>  
 #include <cctype>  
 #include <cmath>  
 #include <cstdio>  
 #include <cstdlib>  
 #include <cstring>  
 #include <climits>  
 #include <iostream>  
 #include <sstream>  
 #include <iomanip>  
 #include <string>  
 #include <vector>  
 #include <list>  
 #include <set>  
 #include <map>  
 #include <stack>  
 #include <queue>  
 #include <algorithm>  
 #include <iterator>  
 #include <utility>  
 using namespace std;  
 template< class T > T _abs(T n) { return (n < 0 ? -n : n); }  
 template< class T > T _max(T a, T b) { return (!(a < b) ? a : b); }  
 template< class T > T _min(T a, T b) { return (a < b ? a : b); }  
 template< class T > T sq(T x) { return x * x; }  
 template< class T > T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a%b) : a); }  
 template< class T > T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); }  
 template< class T > bool inside(T a, T b, T c) { return a<=b && b<=c; }  
 template< class T > void setmax(T &a, T b) { if(a < b) a = b; }  
 template< class T > void setmin(T &a, T b) { if(b < a) a = b; }  
 #define MP(x, y) make_pair(x, y)  
 #define REV(s, e) reverse(s, e)  
 #define SET(p) memset(p, -1, sizeof(p))  
 #define CLR(p) memset(p, 0, sizeof(p))  
 #define MEM(p, v) memset(p, v, sizeof(p))  
 #define CPY(d, s) memcpy(d, s, sizeof(s))  
 #define READ(f) freopen(f, "r", stdin)  
 #define WRITE(f) freopen(f, "w", stdout)  
 #define ALL(c) c.begin(), c.end()  
 #define SIZE(c) (int)c.size()  
 #define PB(x) push_back(x)  
 #define ff first  
 #define ss second  
 #define i64 __int64  
 #define ld long double  
 #define pii pair< int, int >  
 #define psi pair< string, int >  
 const double EPS = 1e-9;  
 const double BIG = 1e19;  
 const int INF = 0x7f7f7f7f;  
 int main() { 

//READ("in.txt");  
   //WRITE("out.txt");  
   return 0;  
 }   


A Blog about Programming,Algorithms,Coding Competitions, and Discrete Mathematics!
You are probably interested in this post because it touches two complicated areas of programming, Bit Manipulations &Recursion. Indeed it does. I will dig deep into these. Bear with my speed and be patient, you will get it. The best way would be to take a problem and follow through it. There are chances that you might have already heard about this problem but I will try to follow an approach which hopefully will highlight some new things about the problem.

So first the problem. Lets say your friend comes to you and puts a challenge across, Programming Interviews: Implement adding two unsigned numbers without using "+" or "++"?. You being a problem solver, accept the challenge & try to work on a solution. You think, Is there a possibility that by using any in-built operators other then '+', you will be able to solve this? Probably. So you try various operator '-', '*', '%' etc. You put all your effort into it but solution remains elusive. You think that there is no harm in asking for help to get some pointers. Absolutely, no harm. You approach another nerdy friend to get some help on the problem. After seeing the problem, what do you think would be his first response? Think... Well, it is highly likely (if he is a nerd) that he will ask you this question, "Can you try bit operators?". It looks like your friend has taken quite a journey. He asked you this question because he thinks that if a in-built language operator is not an option, can we do what computer itself would be doing? Use bit operators.
So you get a cue. You have some basic idea about bit manipulation. You start working on the program using bit operations. You look at bit array associated with two numbers which need to be added & do some mental wrestling:

19 = 10011
29 = 11101

Since you are aware of bit operations, what is the first thing which crosses your mind? Take a moment & think. May be, you look at the whole binary representation of each number & think that adding bits is simple but how to handle carry from right to left? If you considered the ENTIRE string and thought about moving carry across, there is a problem. The issue is that you are not breaking problem into smaller sub problems. What instead you should have done is this (the last one is important):