Johnson and Trotter algorithm - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Johnson and Trotter algorithm
All permutations of a string using iteration
Program to reverse a string (Iterative and Recursive)
Print reverse of a string using recursion
Write a program to print all permutations of a given string
Print all distinct permutations of a given string with duplicates
Permutations of a given string using STL
All permutations of an array using STL in C++
std::next_permutation and prev_permutation in C++
Lexicographically next permutation in C++
How to print size of array parameter in C++?
How to split a string in C/C++, Python and Java?
boost::split in C++ library
Tokenizing a string in C++
getline() Function and Character Array in C++
getline (string) in C++
How to use getline() in C++ when there are blank lines in input?
scanf() and fscanf() in C
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
Problem With Using fgets()/gets()/scanf() After scanf() in C
Differentiate printable and control character in C ?
rand() and srand() in C/C++
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
Program to calculate value of nCr
Count ways to reach the nth stair using step 1, 2 or 3
Combinational Sum
Print all possible strings of length k that can be formed from a set of n characters
Johnson and Trotter algorithm
All permutations of a string using iteration
Program to reverse a string (Iterative and Recursive)
Print reverse of a string using recursion
Write a program to print all permutations of a given string
Print all distinct permutations of a given string with duplicates
Permutations of a given string using STL
All permutations of an array using STL in C++
std::next_permutation and prev_permutation in C++
Lexicographically next permutation in C++
How to print size of array parameter in C++?
How to split a string in C/C++, Python and Java?
boost::split in C++ library
Tokenizing a string in C++
getline() Function and Character Array in C++
getline (string) in C++
How to use getline() in C++ when there are blank lines in input?
scanf() and fscanf() in C
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
Problem With Using fgets()/gets()/scanf() After scanf() in C
Differentiate printable and control character in C ?
rand() and srand() in C/C++
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations
Program to calculate value of nCr
Count ways to reach the nth stair using step 1, 2 or 3
Combinational Sum
Print all possible strings of length k that can be formed from a set of n characters
Difficulty Level :
Hard
We are given a sequence of numbers from 1 to n. Each permutation in the sequence that we need to generate should differ from the previous permutation by swapping just two adjacent elements of the sequence.
Examples:
Input : n = 3
Output : 123 132 312 321 231 213
         
Input : n = 4
Output : 1234 1243 1423 4123 4132
1432 1342 1324 3124 3142 3412 4312 
4321 3421 3241 3214 2314 2341 2431
4231 4213 2413 2143 2134

A simple solution to use permutations of n-1 elements to generate permutations of n elements.
For example let us see how to generate permutations of size 3 using permutations of size 2.
Permutations of two elements are 1 2 and 2 1.Permutations of three elements can be obtained by inserting 3 at different positions in all permutations of size 2.Inserting 3 in different positions of 1 2 leads to 1 2 3, 1 3 2 and 3 1 2.Inserting 3 in different positions of 2 1 leads to 2 1 3, 2 3 1 and 3 2 1.
To generate permutations of size four, we consider all above six permutations of size three and insert 4 at different positions in every permutation.
Johnson and Trotter algorithmThe Johnson and Trotter algorithm doesn’t require to store all permutations of size n-1 and doesn’t require going through all shorter permutations. Instead, it keeps track of the direction of each element of the permutation.
Find out the largest mobile integer in a particular sequence. A directed integer is said to be mobile if it is greater than its immediate neighbor in the direction it is looking at.Switch this mobile integer and the adjacent integer to which its direction points.Switch the direction of all the elements whose value is greater than the mobile integer value.Repeat the step 1 until unless there is no mobile integer left in the sequence.
Find out the largest mobile integer in a particular sequence. A directed integer is said to be mobile if it is greater than its immediate neighbor in the direction it is looking at.
Switch this mobile integer and the adjacent integer to which its direction points.
Switch the direction of all the elements whose value is greater than the mobile integer value.
Repeat the step 1 until unless there is no mobile integer left in the sequence.
Let us see how to generate permutations of 
size four. We first print 1 2 3 4. Initially 
all directions are right to left.
<1 <2 <3 <4

All mobile numbers are 2, 3 and 4. The largest 
mobile number is 4. We swap 3 and 4. Since 4
is largest, we don't change any direction.
<1 <2 <4 <3

4 is the largest mobile. We swap it with 2.
<1 <4 <2 <3

4 is the largest mobile. We swap it with 1.
<4 <1 <2 <3

3 is largest mobile. We swap it with 2 and 
change directions of greater elements.
4> <1 <3 <2

4 is largest mobile. We swap it with 3.
<4 1> <2 <3

We proceed this way and print all permutations.

Below is the implementation of the approach.
C++
Java
C#
// CPP program to print all permutations using// Johnson and Trotter algorithm.#include <bits/stdc++.h>using namespace std;  bool LEFT_TO_RIGHT = true;bool RIGHT_TO_LEFT = false;  // Utility functions for finding the// position of largest mobile integer in a[].int searchArr(int a[], int n, int mobile){    for (int i = 0; i < n; i++)        if (a[i] == mobile)           return i + 1;}  // To carry out step 1 of the algorithm i.e.// to find the largest mobile integer.int getMobile(int a[], bool dir[], int n){    int mobile_prev = 0, mobile = 0;    for (int i = 0; i < n; i++)    {        // direction 0 represents RIGHT TO LEFT.        if (dir[a[i]-1] == RIGHT_TO_LEFT && i!=0)        {            if (a[i] > a[i-1] && a[i] > mobile_prev)            {                mobile = a[i];                mobile_prev = mobile;            }        }          // direction 1 represents LEFT TO RIGHT.        if (dir[a[i]-1] == LEFT_TO_RIGHT && i!=n-1)        {            if (a[i] > a[i+1] && a[i] > mobile_prev)            {                mobile = a[i];                mobile_prev = mobile;            }        }    }      if (mobile == 0 && mobile_prev == 0)        return 0;    else        return mobile;}  // Prints a single permutationint printOnePerm(int a[], bool dir[], int n){    int mobile = getMobile(a, dir, n);    int pos = searchArr(a, n, mobile);      // swapping the elements according to the    // direction i.e. dir[].    if (dir[a[pos - 1] - 1] ==  RIGHT_TO_LEFT)       swap(a[pos-1], a[pos-2]);      else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT)       swap(a[pos], a[pos-1]);      // changing the directions for elements    // greater than largest mobile integer.    for (int i = 0; i < n; i++)    {        if (a[i] > mobile)        {            if (dir[a[i] - 1] == LEFT_TO_RIGHT)                dir[a[i] - 1] = RIGHT_TO_LEFT;            else if (dir[a[i] - 1] == RIGHT_TO_LEFT)                dir[a[i] - 1] = LEFT_TO_RIGHT;        }    }      for (int i = 0; i < n; i++)        cout << a[i];    cout << " ";}  // To end the algorithm for efficiency it ends// at the factorial of n because number of// permutations possible is just n!.int fact(int n){    int res = 1;    for (int i = 1; i <= n; i++)        res = res * i;    return res;}  // This function mainly calls printOnePerm()// one by one to print all permutations.void printPermutation(int n){    // To store current permutation    int a[n];      // To store current directions    bool dir[n];      // storing the elements from 1 to n and    // printing first permutation.    for (int i = 0; i < n; i++)    {        a[i] = i + 1;        cout << a[i];    }    cout << endl;      // initially all directions are set    // to RIGHT TO LEFT i.e. 0.    for (int i = 0; i < n; i++)        dir[i] =  RIGHT_TO_LEFT;      // for generating permutations in the order.    for (int i = 1; i < fact(n); i++)        printOnePerm(a, dir, n);}  // Driver codeint main(){    int n = 4;    printPermutation(n);    return 0;}
// Java program to print all // permutations using Johnson// and Trotter algorithm.import java.util.*;import java.lang.*;  public class GfG{          private final static boolean LEFT_TO_RIGHT = true;    private final static boolean RIGHT_TO_LEFT = false;      // Utility functions for    // finding the position     // of largest mobile     // integer in a[].    public static int searchArr(int a[], int n,                                    int mobile)    {        for (int i = 0; i < n; i++)                          if (a[i] == mobile)                return i + 1;                  return 0;    }      // To carry out step 1    // of the algorithm i.e.    // to find the largest    // mobile integer.    public static int getMobile(int a[],                   boolean dir[], int n)    {        int mobile_prev = 0, mobile = 0;                  for (int i = 0; i < n; i++)        {            // direction 0 represents            // RIGHT TO LEFT.            if (dir[a[i] - 1] == RIGHT_TO_LEFT &&                                          i != 0)            {                if (a[i] > a[i - 1] &&                             a[i] > mobile_prev)                {                    mobile = a[i];                    mobile_prev = mobile;                }            }              // direction 1 represents            // LEFT TO RIGHT.            if (dir[a[i] - 1] == LEFT_TO_RIGHT &&                                      i ! =n - 1)            {                if (a[i] > a[i + 1] &&                             a[i] > mobile_prev)                {                    mobile = a[i];                    mobile_prev = mobile;                }            }        }              if (mobile == 0 && mobile_prev == 0)            return 0;        else            return mobile;    }      // Prints a single     // permutation    public static int printOnePerm(int a[], boolean dir[],                                                    int n)    {        int mobile = getMobile(a, dir, n);        int pos = searchArr(a, n, mobile);          // swapping the elements        // according to the        // direction i.e. dir[].        if (dir[a[pos - 1] - 1] == RIGHT_TO_LEFT)        {            int temp = a[pos - 1];            a[pos - 1] = a[pos - 2];            a[pos - 2] = temp;        }        else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT)        {            int temp = a[pos];            a[pos] = a[pos - 1];            a[pos - 1] = temp;        }          // changing the directions        // for elements greater         // than largest mobile integer.        for (int i = 0; i < n; i++)        {            if (a[i] > mobile)            {                if (dir[a[i] - 1] == LEFT_TO_RIGHT)                    dir[a[i] - 1] = RIGHT_TO_LEFT;                          else if (dir[a[i] - 1] == RIGHT_TO_LEFT)                    dir[a[i] - 1] = LEFT_TO_RIGHT;            }        }          for (int i = 0; i < n; i++)            System.out.print(a[i]);                  System.out.print(" ");                  return 0;    }      // To end the algorithm    // for efficiency it ends    // at the factorial of n    // because number of    // permutations possible     // is just n!.    public static int fact(int n)    {        int res = 1;              for (int i = 1; i <= n; i++)            res = res * i;        return res;    }      // This function mainly    // calls printOnePerm()    // one by one to print    // all permutations.    public static void printPermutation(int n)    {        // To store current        // permutation        int[] a = new int[n];          // To store current        // directions        boolean[] dir = new boolean[n];          // storing the elements        // from 1 to n and        // printing first permutation.        for (int i = 0; i < n; i++)        {            a[i] = i + 1;            System.out.print(a[i]);        }                  System.out.print("\n");          // initially all directions        // are set to RIGHT TO         // LEFT i.e. 0.        for (int i = 0; i < n; i++)            dir[i] = RIGHT_TO_LEFT;          // for generating permutations        // in the order.        for (int i = 1; i < fact(n); i++)            printOnePerm(a, dir, n);    }          // Driver function     public static void main(String argc[])    {        int n = 4;        printPermutation(n);    }      }  // This code is contributed by Sagar Shukla 
// Java program to print all // permutations using Johnson// and Trotter algorithm.using System;   public class GfG{           private  static bool LEFT_TO_RIGHT = true;    private  static bool RIGHT_TO_LEFT = false;       // Utility functions for    // finding the position     // of largest mobile     // integer in a[].    public static int searchArr(int []a, int n,                                    int mobile)    {        for (int i = 0; i < n; i++)                           if (a[i] == mobile)                return i + 1;                   return 0;    }       // To carry out step 1    // of the algorithm i.e.    // to find the largest    // mobile integer.    public static int getMobile(int []a,                   bool []dir, int n)    {        int mobile_prev = 0, mobile = 0;                   for (int i = 0; i < n; i++)        {            // direction 0 represents            // RIGHT TO LEFT.            if (dir[a[i] - 1] == RIGHT_TO_LEFT &&                                          i != 0)            {                if (a[i] > a[i - 1] &&                             a[i] > mobile_prev)                {                    mobile = a[i];                    mobile_prev = mobile;                }            }               // direction 1 represents            // LEFT TO RIGHT.            if (dir[a[i] - 1] == LEFT_TO_RIGHT && i!=n - 1)            {                if (a[i] > a[i + 1] &&                             a[i] > mobile_prev)                {                    mobile = a[i];                    mobile_prev = mobile;                }            }        }               if (mobile == 0 && mobile_prev == 0)            return 0;        else            return mobile;    }       // Prints a single     // permutation    public static int printOnePerm(int []a, bool []dir,                                                    int n)    {        int mobile = getMobile(a, dir, n);        int pos = searchArr(a, n, mobile);           // swapping the elements        // according to the        // direction i.e. dir[].        if (dir[a[pos - 1] - 1] == RIGHT_TO_LEFT)        {            int temp = a[pos - 1];            a[pos - 1] = a[pos - 2];            a[pos - 2] = temp;        }        else if (dir[a[pos - 1] - 1] == LEFT_TO_RIGHT)        {            int temp = a[pos];            a[pos] = a[pos - 1];            a[pos - 1] = temp;        }           // changing the directions        // for elements greater         // than largest mobile integer.        for (int i = 0; i < n; i++)        {            if (a[i] > mobile)            {                if (dir[a[i] - 1] == LEFT_TO_RIGHT)                    dir[a[i] - 1] = RIGHT_TO_LEFT;                           else if (dir[a[i] - 1] == RIGHT_TO_LEFT)                    dir[a[i] - 1] = LEFT_TO_RIGHT;            }        }           for (int i = 0; i < n; i++)            Console.Write(a[i]);                   Console.Write(" ");                   return 0;    }       // To end the algorithm    // for efficiency it ends    // at the factorial of n    // because number of    // permutations possible     // is just n!.    public static int fact(int n)    {        int res = 1;               for (int i = 1; i <= n; i++)            res = res * i;        return res;    }       // This function mainly    // calls printOnePerm()    // one by one to print    // all permutations.    public static void printPermutation(int n)    {        // To store current        // permutation        int []a = new int[n];           // To store current        // directions        bool []dir = new bool[n];           // storing the elements        // from 1 to n and        // printing first permutation.        for (int i = 0; i < n; i++)        {            a[i] = i + 1;            Console.Write(a[i]);        }                   Console.Write("\n");           // initially all directions        // are set to RIGHT TO         // LEFT i.e. 0.        for (int i = 0; i < n; i++)            dir[i] = RIGHT_TO_LEFT;           // for generating permutations        // in the order.        for (int i = 1; i < fact(n); i++)            printOnePerm(a, dir, n);    }           // Driver function     public static void Main()    {        int n = 4;        printPermutation(n);    }       }   // This code is contributed by nitin mittal.
1234 1243 1423 4123 4132 1432 1342 1324
3124 3142 3412 4312 4321 3421 3241 3214
2314 2341 2431 4231 4213 2413 2143 2134

nitin mittal
Jean-PhilippeDrecourt
Combinatorial
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Heap's Algorithm for generating permutations
Distinct permutations of the string | Set 2
Make all combinations of size k
Count Derangements (Permutation such that no element appears in its original position)
Print all subsets of given size of a set
Find all distinct subsets of a given set using BitMasking Approach
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Print all permutations in sorted (lexicographic) order