SlideShare a Scribd company logo
TIME AND SPACE COMPLEXITY
Time Complexity

The total number of steps involved in a solution to solve a problem is the function of the size of the
problem, which is the measure of that problem’s time complexity.

some general order that we can consider

       (c) < O(log n) < O(n) < O(n log n) < O(nc) < O(cn) < O(n!), where c is some constant.

Space Complexity
Space complexity is measured by using polynomial amounts of memory, with an infinite amount of time.

The difference between space complexity and time complexity is that space can be reused.
Space complexity is not affected by determinism or nondeterminism.

       Amount of computer memory required during the program execution, as a function of the
       input size

A small amount of space, deterministic machines can simulate nondeterministic machines,
where as in time complexity, time increase exponentially in this case. A nondeterministic
TM using O(n) space can be changed to a deterministic TM using only O 2(n) space.

Complexity: why bother?

Estimation/Prediction
             When you write/run a program, you need to be able to predict its
             needs, its requirements.
Usual requirements
             - execution time
             - memory space
Quantities to estimate
              execution time  time complexity
              memory space  space complexity



It is pointless to run a program that requires:
                 - 6TeraB of RAM on a desktop machine;
                 - 10,000 years to run. . .
You do not want to wait for an hour:
        - for the result of your query on Google;
        - when you are checking your bank account online;
        - when you are opening a picture file on Photoshop;
        - etc.

 It is important to write efficient algorithms
Complexity Classes

                  Deterministic Polynomial Time
P-complete        Hardest problems in P solvable on parallel computers
                  Nondeterministic polynomial time and YES answers checkable in
                  polynomial time
                  Nondeterministic polynomial time and NO answers checkable in
Co-NP
                  polynomial time
NP-
                  Hardest problems in NP
complete
Co-NP-complete    Hardest problems in CO-NP
NP-hard           At least as hard as NP-complete problems
NC                Solvable parallel computation efficiency
PSPACE            Polynomial memory with unlimited time
PSPACE-
complete          Hardest problems in PSPACE
EXPTIME           Exponential time
EXPSPACE          Exponential memory with unlimited time
BQP               Polynomial time on a quantum computer

Find the greatest common divisor (GCD) of two integers, m
and n.


Program (in C):
          int gcd(int m, int n)
          /* precondition: m>0 and n>0.Let g=gcd(m,n). */
          {
            while( m > 0 )
            { /* invariant: gcd(m,n)=g */
            if( n > m )
            { int t = m; m = n; n = t; } /* swap */
            /* m >= n > 0 */
            m -= n;
            }
            return n;
          }

At the start of each iteration of the loop, either n>m or m?n.

          (i) If m?n, then m is replaced by m-n which is smaller than the previous value of m, and still
          non-negative.
          (ii) If n>m, m and n are exchanged, and at the next iteration case (i) will apply.
So at each iteration, max(m,n) either remains unchanged (for just one iteration) or it decreases.
This cannot go on for ever because m and n are integers (this fact is important), and eventually a
lower limit is reached, when m=0 and n=g.

So the algorithm does terminate.

Good test values would include:

   •   special cases where m or n equals 1, or
   •   m, or n, or both equal small primes 2, 3, 5, …, or
   •   products of two small primes such as p1×p2 and p3×p2,
   •   some larger values, but ones where you know the answers,
   •   swapped values, (x,y) and (y,x), because gcd(m,n)=gcd(n,m).

The objective in testing is to "exercise" all paths through the code, in different combinations.

We can also consider the best,average and worst cases.

Average vs. worst-case complexity

Definition (Worst-case complexity)

       The worst-case complexity is the complexity of an algorithm when
       the input is the worst possible with respect to complexity.

Definition (Average complexity)

       The average complexity is the complexity of an algorithm that is
       averaged over all the possible inputs (assuming a uniform
       distribution over the inputs).

       We assume that the complexity of the algorithm is T(i) for an
       input i. The set of possible inputs of size n is denoted In.


Big-O Notation Analysis of Algorithms
Big Oh Notation-

       A convenient way of describing the growth rate of a function and hence the time complexity
       of an algorithm.

       Let n be the size of the input and f (n), g(n) be positive functions of n.

       The time efficiency of almost all of the algorithms we have discussed can be characterized by
       only a few growth rate functions:

I. O(l) - constant time

       This means that the algorithm requires the same fixed number of steps regardless of the size
       of the task.

       Examples (assuming a reasonable implementation of the task):
A. Push and Pop operations for a stack (containing n elements);
       B. Insert and Remove operations for a queue.

II. O(n) - linear time
       This means that the algorithm requires a number of steps proportional to the size of the task.

       Examples (assuming a reasonable implementation of the task):

       A. Traversal of a list (a linked list or an array) with n elements;
       B. Finding the maximum or minimum element in a list, or sequential search in an unsorted
       list of n elements;
       C. Traversal of a tree with n nodes;
       D. Calculating iteratively n-factorial; finding iteratively the nth Fibonacci number.

III. O(n2) - quadratic time

The number of operations is proportional to the size of the task squared.

Examples:
      A. Some more simplistic sorting algorithms, for instance a selection sort of n elements;
      B. Comparing two two-dimensional arrays of size n by n;
      C. Finding duplicates in an unsorted list of n elements (implemented with two nested loops).

IV. O(log n) - logarithmic time

Examples:
      A. Binary search in a sorted list of n elements;
      B. Insert and Find operations for a binary search tree with n nodes;
      C. Insert and Remove operations for a heap with n nodes.

V. O(n log n) - "n log n " time

       Examples:
       A. More advanced sorting algorithms - quicksort, mergesort

VI. O(an) (a > 1) - exponential time
Examples:
       A. Recursive Fibonacci implementation
       B. Towers of Hanoi
       C. Generating all permutations of n symbols



The best time in the above list is obviously constant time, and the worst is exponential time which, as
we have seen, quickly overwhelms even the fastest computers even for relatively small n.
Polynomial growth (linear, quadratic, cubic, etc.) is considered manageable as compared to
exponential growth.

Order of asymptotic behavior of the functions from the above list:

Using the "<" sign informally, we can say that

O(l) < O(log n) < O(n) < O(n log n) < O(n2) < O(n3) < O(an)
A word about O(log n) growth:

As we know from the Change of Base Theorem, for any a, b > 0, and a, b != 1




Therefore,

loga n = C logb n


where C is a constant equal to loga b.

Since functions that differ only by a constant factor have the same order of growth, O(log2 n) is the
same as O(log n).

Therefore, when we talk about logarithmic growth, the base of the logarithm is not important, and we
can say simply O(log n).

A word about Big-O when a function is the sum of several terms:

If a function (which describes the order of growth of an algorithm) is a sum of several terms, its order
of growth is determined by the fastest growing term. In particular, if we have a polynomial

p(n) = aknk + ak-1nk-1 + … + a1n + a0

its growth is of the order nk:

p(n) = O(nk)


Example:

More Related Content

What's hot

Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
V.V.Vanniaperumal College for Women
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
vikas dhakane
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back trackingTech_MX
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
Mohamed Loey
 
Bruteforce algorithm
Bruteforce algorithmBruteforce algorithm
Bruteforce algorithm
Rezwan Siam
 
Queue ppt
Queue pptQueue ppt
Queue ppt
SouravKumar328
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
Dr. C.V. Suresh Babu
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
Rishabh Soni
 
Arrays
ArraysArrays
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 
15 puzzle problem using branch and bound
15 puzzle problem using branch and bound15 puzzle problem using branch and bound
15 puzzle problem using branch and bound
Abhishek Singh
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
Prof. Dr. K. Adisesha
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
swapnac12
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
Kevin Jadiya
 
Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
Daffodil International University
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
Ashim Lamichhane
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
Shuvongkor Barman
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
shameen khan
 

What's hot (20)

Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Graph coloring problem
Graph coloring problemGraph coloring problem
Graph coloring problem
 
I. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHMI. AO* SEARCH ALGORITHM
I. AO* SEARCH ALGORITHM
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Bruteforce algorithm
Bruteforce algorithmBruteforce algorithm
Bruteforce algorithm
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
Arrays
ArraysArrays
Arrays
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
15 puzzle problem using branch and bound
15 puzzle problem using branch and bound15 puzzle problem using branch and bound
15 puzzle problem using branch and bound
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
Graph coloring using backtracking
Graph coloring using backtrackingGraph coloring using backtracking
Graph coloring using backtracking
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 

Viewers also liked

Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
Hossain Md Shakhawat
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
Dr. Rajdeep Chatterjee
 
Sorting
SortingSorting
358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14
sumitbardhan
 
Lecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic SortingLecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic SortingHaitham El-Ghareeb
 
Sorting
SortingSorting
Sorting
Gopi Saiteja
 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
Emertxe Information Technologies Pvt Ltd
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
Shakila Mahjabin
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
Muhammad Muzammal
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
Arvind Krishnaa
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Mohammed Hussein
 

Viewers also liked (13)

Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
 
Sorting
SortingSorting
Sorting
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Sorting
SortingSorting
Sorting
 
358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14
 
Lecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic SortingLecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic Sorting
 
Sorting
SortingSorting
Sorting
 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 

Similar to Time and space complexity

Asymptotics 140510003721-phpapp02
Asymptotics 140510003721-phpapp02Asymptotics 140510003721-phpapp02
Asymptotics 140510003721-phpapp02
mansab MIRZA
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematical
babuk110
 
Asymptotic Notations.pptx
Asymptotic Notations.pptxAsymptotic Notations.pptx
Asymptotic Notations.pptx
SunilWork1
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV Syllabus
NANDINI SHARMA
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
Mallikarjun Biradar
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
2022cspaawan12556
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
Abdullah Al-hazmy
 
Module 1 notes of data warehousing and data
Module 1 notes of data warehousing and dataModule 1 notes of data warehousing and data
Module 1 notes of data warehousing and data
vijipersonal2012
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
Tanya Makkar
 
Lec03 04-time complexity
Lec03 04-time complexityLec03 04-time complexity
Lec03 04-time complexityAbbas Ali
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
NagendraK18
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysischidabdu
 
Lec1
Lec1Lec1
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Unit 1.pptx
Unit 1.pptxUnit 1.pptx
Unit 1.pptx
DeepakYadav656387
 
Aad introduction
Aad introductionAad introduction
Aad introductionMr SMAK
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
KokilaK25
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
http://algorithmtraining.com/advanced-python-training-hyderabad/
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
http://algorithmtraining.com/advanced-python-training-hyderabad/
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
http://algorithmtraining.com/advanced-python-training-hyderabad/
 

Similar to Time and space complexity (20)

Asymptotics 140510003721-phpapp02
Asymptotics 140510003721-phpapp02Asymptotics 140510003721-phpapp02
Asymptotics 140510003721-phpapp02
 
Data Structure & Algorithms - Mathematical
Data Structure & Algorithms - MathematicalData Structure & Algorithms - Mathematical
Data Structure & Algorithms - Mathematical
 
Asymptotic Notations.pptx
Asymptotic Notations.pptxAsymptotic Notations.pptx
Asymptotic Notations.pptx
 
Basic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV SyllabusBasic Computer Engineering Unit II as per RGPV Syllabus
Basic Computer Engineering Unit II as per RGPV Syllabus
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...DSA Complexity.pptx   What is Complexity Analysis? What is the need for Compl...
DSA Complexity.pptx What is Complexity Analysis? What is the need for Compl...
 
Data Structures- Part2 analysis tools
Data Structures- Part2 analysis toolsData Structures- Part2 analysis tools
Data Structures- Part2 analysis tools
 
Module 1 notes of data warehousing and data
Module 1 notes of data warehousing and dataModule 1 notes of data warehousing and data
Module 1 notes of data warehousing and data
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
 
Lec03 04-time complexity
Lec03 04-time complexityLec03 04-time complexity
Lec03 04-time complexity
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
 
Lec1
Lec1Lec1
Lec1
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Unit 1.pptx
Unit 1.pptxUnit 1.pptx
Unit 1.pptx
 
Aad introduction
Aad introductionAad introduction
Aad introduction
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
 

More from Ankit Katiyar

Transportation and assignment_problem
Transportation and assignment_problemTransportation and assignment_problem
Transportation and assignment_problemAnkit Katiyar
 
The oc curve_of_attribute_acceptance_plans
The oc curve_of_attribute_acceptance_plansThe oc curve_of_attribute_acceptance_plans
The oc curve_of_attribute_acceptance_plansAnkit Katiyar
 
Simple queuingmodelspdf
Simple queuingmodelspdfSimple queuingmodelspdf
Simple queuingmodelspdfAnkit Katiyar
 
Scatter diagrams and correlation and simple linear regresssion
Scatter diagrams and correlation and simple linear regresssionScatter diagrams and correlation and simple linear regresssion
Scatter diagrams and correlation and simple linear regresssionAnkit Katiyar
 
Probability mass functions and probability density functions
Probability mass functions and probability density functionsProbability mass functions and probability density functions
Probability mass functions and probability density functionsAnkit Katiyar
 
Introduction to basic statistics
Introduction to basic statisticsIntroduction to basic statistics
Introduction to basic statisticsAnkit Katiyar
 
Conceptual foundations statistics and probability
Conceptual foundations   statistics and probabilityConceptual foundations   statistics and probability
Conceptual foundations statistics and probabilityAnkit Katiyar
 
Applied statistics and probability for engineers solution montgomery && runger
Applied statistics and probability for engineers solution   montgomery && rungerApplied statistics and probability for engineers solution   montgomery && runger
Applied statistics and probability for engineers solution montgomery && rungerAnkit Katiyar
 
A hand kano-model-boston_upa_may-12-2004
A hand kano-model-boston_upa_may-12-2004A hand kano-model-boston_upa_may-12-2004
A hand kano-model-boston_upa_may-12-2004Ankit Katiyar
 

More from Ankit Katiyar (20)

Transportation and assignment_problem
Transportation and assignment_problemTransportation and assignment_problem
Transportation and assignment_problem
 
The oc curve_of_attribute_acceptance_plans
The oc curve_of_attribute_acceptance_plansThe oc curve_of_attribute_acceptance_plans
The oc curve_of_attribute_acceptance_plans
 
Stat methchapter
Stat methchapterStat methchapter
Stat methchapter
 
Simple queuingmodelspdf
Simple queuingmodelspdfSimple queuingmodelspdf
Simple queuingmodelspdf
 
Scatter diagrams and correlation and simple linear regresssion
Scatter diagrams and correlation and simple linear regresssionScatter diagrams and correlation and simple linear regresssion
Scatter diagrams and correlation and simple linear regresssion
 
Queueing 3
Queueing 3Queueing 3
Queueing 3
 
Queueing 2
Queueing 2Queueing 2
Queueing 2
 
Queueing
QueueingQueueing
Queueing
 
Probability mass functions and probability density functions
Probability mass functions and probability density functionsProbability mass functions and probability density functions
Probability mass functions and probability density functions
 
Lesson2
Lesson2Lesson2
Lesson2
 
Lecture18
Lecture18Lecture18
Lecture18
 
Lect17
Lect17Lect17
Lect17
 
Lect 02
Lect 02Lect 02
Lect 02
 
Kano
KanoKano
Kano
 
Introduction to basic statistics
Introduction to basic statisticsIntroduction to basic statistics
Introduction to basic statistics
 
Conceptual foundations statistics and probability
Conceptual foundations   statistics and probabilityConceptual foundations   statistics and probability
Conceptual foundations statistics and probability
 
B.lect1
B.lect1B.lect1
B.lect1
 
Axioms
AxiomsAxioms
Axioms
 
Applied statistics and probability for engineers solution montgomery && runger
Applied statistics and probability for engineers solution   montgomery && rungerApplied statistics and probability for engineers solution   montgomery && runger
Applied statistics and probability for engineers solution montgomery && runger
 
A hand kano-model-boston_upa_may-12-2004
A hand kano-model-boston_upa_may-12-2004A hand kano-model-boston_upa_may-12-2004
A hand kano-model-boston_upa_may-12-2004
 

Time and space complexity

  • 1. TIME AND SPACE COMPLEXITY Time Complexity The total number of steps involved in a solution to solve a problem is the function of the size of the problem, which is the measure of that problem’s time complexity. some general order that we can consider (c) < O(log n) < O(n) < O(n log n) < O(nc) < O(cn) < O(n!), where c is some constant. Space Complexity Space complexity is measured by using polynomial amounts of memory, with an infinite amount of time. The difference between space complexity and time complexity is that space can be reused. Space complexity is not affected by determinism or nondeterminism. Amount of computer memory required during the program execution, as a function of the input size A small amount of space, deterministic machines can simulate nondeterministic machines, where as in time complexity, time increase exponentially in this case. A nondeterministic TM using O(n) space can be changed to a deterministic TM using only O 2(n) space. Complexity: why bother? Estimation/Prediction When you write/run a program, you need to be able to predict its needs, its requirements. Usual requirements - execution time - memory space Quantities to estimate execution time  time complexity memory space  space complexity It is pointless to run a program that requires: - 6TeraB of RAM on a desktop machine; - 10,000 years to run. . . You do not want to wait for an hour: - for the result of your query on Google; - when you are checking your bank account online; - when you are opening a picture file on Photoshop; - etc.  It is important to write efficient algorithms
  • 2. Complexity Classes Deterministic Polynomial Time P-complete Hardest problems in P solvable on parallel computers Nondeterministic polynomial time and YES answers checkable in polynomial time Nondeterministic polynomial time and NO answers checkable in Co-NP polynomial time NP- Hardest problems in NP complete Co-NP-complete Hardest problems in CO-NP NP-hard At least as hard as NP-complete problems NC Solvable parallel computation efficiency PSPACE Polynomial memory with unlimited time PSPACE- complete Hardest problems in PSPACE EXPTIME Exponential time EXPSPACE Exponential memory with unlimited time BQP Polynomial time on a quantum computer Find the greatest common divisor (GCD) of two integers, m and n. Program (in C): int gcd(int m, int n) /* precondition: m>0 and n>0.Let g=gcd(m,n). */ { while( m > 0 ) { /* invariant: gcd(m,n)=g */ if( n > m ) { int t = m; m = n; n = t; } /* swap */ /* m >= n > 0 */ m -= n; } return n; } At the start of each iteration of the loop, either n>m or m?n. (i) If m?n, then m is replaced by m-n which is smaller than the previous value of m, and still non-negative. (ii) If n>m, m and n are exchanged, and at the next iteration case (i) will apply.
  • 3. So at each iteration, max(m,n) either remains unchanged (for just one iteration) or it decreases. This cannot go on for ever because m and n are integers (this fact is important), and eventually a lower limit is reached, when m=0 and n=g. So the algorithm does terminate. Good test values would include: • special cases where m or n equals 1, or • m, or n, or both equal small primes 2, 3, 5, …, or • products of two small primes such as p1×p2 and p3×p2, • some larger values, but ones where you know the answers, • swapped values, (x,y) and (y,x), because gcd(m,n)=gcd(n,m). The objective in testing is to "exercise" all paths through the code, in different combinations. We can also consider the best,average and worst cases. Average vs. worst-case complexity Definition (Worst-case complexity) The worst-case complexity is the complexity of an algorithm when the input is the worst possible with respect to complexity. Definition (Average complexity) The average complexity is the complexity of an algorithm that is averaged over all the possible inputs (assuming a uniform distribution over the inputs). We assume that the complexity of the algorithm is T(i) for an input i. The set of possible inputs of size n is denoted In. Big-O Notation Analysis of Algorithms Big Oh Notation- A convenient way of describing the growth rate of a function and hence the time complexity of an algorithm. Let n be the size of the input and f (n), g(n) be positive functions of n. The time efficiency of almost all of the algorithms we have discussed can be characterized by only a few growth rate functions: I. O(l) - constant time This means that the algorithm requires the same fixed number of steps regardless of the size of the task. Examples (assuming a reasonable implementation of the task):
  • 4. A. Push and Pop operations for a stack (containing n elements); B. Insert and Remove operations for a queue. II. O(n) - linear time This means that the algorithm requires a number of steps proportional to the size of the task. Examples (assuming a reasonable implementation of the task): A. Traversal of a list (a linked list or an array) with n elements; B. Finding the maximum or minimum element in a list, or sequential search in an unsorted list of n elements; C. Traversal of a tree with n nodes; D. Calculating iteratively n-factorial; finding iteratively the nth Fibonacci number. III. O(n2) - quadratic time The number of operations is proportional to the size of the task squared. Examples: A. Some more simplistic sorting algorithms, for instance a selection sort of n elements; B. Comparing two two-dimensional arrays of size n by n; C. Finding duplicates in an unsorted list of n elements (implemented with two nested loops). IV. O(log n) - logarithmic time Examples: A. Binary search in a sorted list of n elements; B. Insert and Find operations for a binary search tree with n nodes; C. Insert and Remove operations for a heap with n nodes. V. O(n log n) - "n log n " time Examples: A. More advanced sorting algorithms - quicksort, mergesort VI. O(an) (a > 1) - exponential time Examples: A. Recursive Fibonacci implementation B. Towers of Hanoi C. Generating all permutations of n symbols The best time in the above list is obviously constant time, and the worst is exponential time which, as we have seen, quickly overwhelms even the fastest computers even for relatively small n. Polynomial growth (linear, quadratic, cubic, etc.) is considered manageable as compared to exponential growth. Order of asymptotic behavior of the functions from the above list: Using the "<" sign informally, we can say that O(l) < O(log n) < O(n) < O(n log n) < O(n2) < O(n3) < O(an)
  • 5. A word about O(log n) growth: As we know from the Change of Base Theorem, for any a, b > 0, and a, b != 1 Therefore, loga n = C logb n where C is a constant equal to loga b. Since functions that differ only by a constant factor have the same order of growth, O(log2 n) is the same as O(log n). Therefore, when we talk about logarithmic growth, the base of the logarithm is not important, and we can say simply O(log n). A word about Big-O when a function is the sum of several terms: If a function (which describes the order of growth of an algorithm) is a sum of several terms, its order of growth is determined by the fastest growing term. In particular, if we have a polynomial p(n) = aknk + ak-1nk-1 + … + a1n + a0 its growth is of the order nk: p(n) = O(nk) Example: