Repository: kunal-kushwaha/DSA-Bootcamp-Java Branch: main Commit: 6bc4d8bf8ac5 Files: 453 Total size: 484.8 KB Directory structure: gitextract_kj9lo73p/ ├── .gitignore ├── README.md ├── SYLLABUS.md ├── assignments/ │ ├── 01-flow-of-program.md │ ├── 02-first-java.md │ ├── 03-conditionals-loops.md │ ├── 04-functions.md │ ├── 05-arrays.md │ ├── 06-searching.md │ ├── 07-sorting.md │ ├── 08-strings.md │ ├── 09-patterns.md │ ├── 10-recursion.md │ ├── 11-bitwise.md │ ├── 12-math.md │ ├── 13-complexities.md │ ├── 14-oop.md │ ├── 15-linkedlist.md │ ├── 16-stack-queue.md │ ├── 17-trees.md │ └── 18-heaps.md └── lectures/ ├── 05-first-java-program/ │ ├── first-idea-program/ │ │ ├── .idea/ │ │ │ ├── .gitignore │ │ │ ├── description.html │ │ │ ├── encodings.xml │ │ │ ├── misc.xml │ │ │ ├── modules.xml │ │ │ ├── project-template.xml │ │ │ └── vcs.xml │ │ ├── first-idea-program.iml │ │ └── src/ │ │ └── com/ │ │ └── kunal/ │ │ ├── Basics.java │ │ ├── Inputs.java │ │ ├── Main.java │ │ ├── Prime.java │ │ ├── Primitives.java │ │ ├── Sum.java │ │ ├── Temperature.java │ │ └── TypeCasting.java │ ├── first-tutorial/ │ │ ├── Demo.java │ │ └── Main.java │ └── notes/ │ ├── literals.txt │ ├── notes.txt │ └── type_conversion&casting.txt ├── 06-conditions-loops/ │ ├── code/ │ │ ├── .idea/ │ │ │ ├── .gitignore │ │ │ ├── description.html │ │ │ ├── encodings.xml │ │ │ ├── misc.xml │ │ │ ├── modules.xml │ │ │ ├── project-template.xml │ │ │ ├── uiDesigner.xml │ │ │ └── vcs.xml │ │ ├── code.iml │ │ └── src/ │ │ └── com/ │ │ └── kunal/ │ │ ├── Calculator.java │ │ ├── CaseCheck.java │ │ ├── Conditionals.java │ │ ├── CountNums.java │ │ ├── Fibo.java │ │ ├── Largest.java │ │ ├── Loops.java │ │ └── Reverse.java │ └── switch/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── src/ │ │ └── com/ │ │ └── kunal/ │ │ ├── Main.java │ │ └── NestedSwitch.java │ └── switch.iml ├── 07-methods/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── ChangeValue.java │ ├── Greeting.java │ ├── Main.java │ ├── Overloading.java │ ├── PassingExample.java │ ├── Questions.java │ ├── Scope.java │ ├── Shadowing.java │ ├── StringExample.java │ ├── Sum.java │ ├── Swap.java │ └── VarArgs.java ├── 08-arrays/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── ArrayListExample.java │ ├── ColNoFixed.java │ ├── Input.java │ ├── Main.java │ ├── Max.java │ ├── MultiAL.java │ ├── MultiDimension.java │ ├── PassinginFunctions.java │ └── Swap.java ├── 09-linear search/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── EvenDigits.java │ ├── FindMin.java │ ├── Main.java │ ├── MaxWealth.java │ ├── SearchIn2DArray.java │ ├── SearchInRange.java │ └── SearchInStrings.java ├── 10-binary search/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ ├── uiDesigner.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── BinarySearch.java │ ├── Ceiling.java │ ├── FirstAndLastPosition.java │ ├── Floor.java │ ├── InfiniteArray.java │ ├── Mountain.java │ ├── OrderAgnosticBS.java │ ├── RBS.java │ ├── RotationCount.java │ ├── RowColMatrix.java │ ├── SearchInMountain.java │ ├── SmallestLetter.java │ ├── SortedMatrix.java │ └── SplitArray.java ├── 11-sorting/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ ├── uiDesigner.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── CyclicSort.java │ ├── FindAllDuplicates.java │ ├── FindAllMissing.java │ ├── FindDuplicate.java │ ├── Main.java │ ├── MissingNumber.java │ ├── MissingPositive.java │ └── SetMismatch.java ├── 12-strings/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── Comparison.java │ ├── Main.java │ ├── Methods.java │ ├── Operators.java │ ├── Output.java │ ├── Palin.java │ ├── Performance.java │ ├── PrettyPrinting.java │ ├── SB.java │ └── placeholders_list.txt ├── 13-patterns/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ └── Main.java ├── 14-recursion/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ ├── uiDesigner.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── arrays/ │ │ ├── Find.java │ │ ├── RBS.java │ │ └── Sorted.java │ ├── backtracking/ │ │ ├── AllPaths.java │ │ ├── Maze.java │ │ ├── NKnights.java │ │ ├── NQueens.java │ │ └── SudokuSolver.java │ ├── easy/ │ │ ├── CountZeros.java │ │ ├── DigitProduct.java │ │ ├── DigitSum.java │ │ ├── Fact.java │ │ ├── Nto1.java │ │ ├── Palindrome.java │ │ ├── Reverse.java │ │ ├── Steps.java │ │ └── Sum.java │ ├── intro/ │ │ ├── BS.java │ │ ├── Fibo.java │ │ ├── Message.java │ │ ├── NumbersExample.java │ │ └── NumbersExampleRecursion.java │ ├── patterns/ │ │ └── Triangle.java │ ├── sorting/ │ │ ├── MergeSort.java │ │ └── QuickSort.java │ └── strings/ │ ├── Ascii.java │ ├── Dice.java │ ├── Permutations.java │ ├── PhonePad.java │ ├── Stream.java │ ├── SubSeq.java │ └── SubSet.java ├── 15-complexity/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ └── Fibo.java ├── 16-math/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ ├── uiDesigner.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── bitwise/ │ │ ├── FindUnique.java │ │ ├── FlipImage.java │ │ ├── MagicNumber.java │ │ ├── NoOfDigits.java │ │ ├── OddEven.java │ │ ├── PowOfTwo.java │ │ ├── Power.java │ │ ├── RangeXOR.java │ │ └── SetBits.java │ └── maths/ │ ├── BinarySearchSQRT.java │ ├── Factors.java │ ├── GCD_LCM.java │ ├── NewtonSQRT.java │ ├── Prime.java │ └── Seive.java ├── 17-oop/ │ ├── code/ │ │ ├── .idea/ │ │ │ ├── .gitignore │ │ │ ├── description.html │ │ │ ├── encodings.xml │ │ │ ├── misc.xml │ │ │ ├── modules.xml │ │ │ ├── project-template.xml │ │ │ ├── uiDesigner.xml │ │ │ └── vcs.xml │ │ ├── code.iml │ │ └── src/ │ │ └── com/ │ │ └── kunal/ │ │ ├── abstractDemo/ │ │ │ ├── Daughter.java │ │ │ ├── Main.java │ │ │ ├── Parent.java │ │ │ ├── Parent2.java │ │ │ └── Son.java │ │ ├── access/ │ │ │ ├── A.java │ │ │ ├── Main.java │ │ │ ├── ObjectDemo.java │ │ │ └── SubClass.java │ │ ├── cloning/ │ │ │ ├── Human.java │ │ │ └── Main.java │ │ ├── collections/ │ │ │ └── Main.java │ │ ├── enumExamples/ │ │ │ ├── A.java │ │ │ └── Basic.java │ │ ├── exceptionHandling/ │ │ │ ├── Demo.java │ │ │ ├── Main.java │ │ │ └── MyException.java │ │ ├── generics/ │ │ │ ├── CustomArrayList.java │ │ │ ├── CustomGenArrayList.java │ │ │ ├── GenericInterface.java │ │ │ ├── LambdaFunctions.java │ │ │ ├── Main.java │ │ │ ├── WildcardExample.java │ │ │ └── comparing/ │ │ │ ├── Main.java │ │ │ └── Student.java │ │ ├── interfaces/ │ │ │ ├── Brake.java │ │ │ ├── CDPlayer.java │ │ │ ├── Car.java │ │ │ ├── ElecticEngine.java │ │ │ ├── Engine.java │ │ │ ├── Main.java │ │ │ ├── Media.java │ │ │ ├── NiceCar.java │ │ │ ├── PowerEngine.java │ │ │ ├── extendDemo/ │ │ │ │ ├── A.java │ │ │ │ ├── B.java │ │ │ │ └── Main.java │ │ │ ├── extendDemo2/ │ │ │ │ ├── A.java │ │ │ │ ├── B.java │ │ │ │ └── Main.java │ │ │ └── nested/ │ │ │ ├── A.java │ │ │ └── Main.java │ │ ├── introduction/ │ │ │ ├── Main.java │ │ │ └── WrapperExample.java │ │ ├── packages/ │ │ │ ├── a/ │ │ │ │ └── Greeting.java │ │ │ └── b/ │ │ │ ├── Greeting.java │ │ │ └── Message.java │ │ ├── properties/ │ │ │ ├── inheritance/ │ │ │ │ ├── Box.java │ │ │ │ ├── BoxColor.java │ │ │ │ ├── BoxPrice.java │ │ │ │ ├── BoxWeight.java │ │ │ │ └── Main.java │ │ │ └── polymorphism/ │ │ │ ├── Circle.java │ │ │ ├── Main.java │ │ │ ├── Numbers.java │ │ │ ├── ObjectPrint.java │ │ │ ├── Shapes.java │ │ │ ├── Square.java │ │ │ └── Triangle.java │ │ ├── singleton/ │ │ │ ├── Main.java │ │ │ ├── NotSubClass.java │ │ │ ├── Singleton.java │ │ │ └── SubClass.java │ │ └── staticExample/ │ │ ├── Human.java │ │ ├── InnerClasses.java │ │ ├── Main.java │ │ └── StaticBlock.java │ └── notes/ │ ├── abstract.txt │ ├── access_control.txt │ ├── classes.txt │ ├── constructors_this_finalize.txt │ ├── inheritance.txt │ ├── interface.txt │ ├── notes.txt │ ├── overloading.txt │ ├── overriding.txt │ ├── packages.txt │ └── static.txt ├── 18-linkedlist/ │ └── code/ │ ├── .idea/ │ │ ├── .gitignore │ │ ├── description.html │ │ ├── encodings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ ├── project-template.xml │ │ ├── uiDesigner.xml │ │ └── vcs.xml │ ├── code.iml │ └── src/ │ └── com/ │ └── kunal/ │ ├── CLL.java │ ├── DLL.java │ ├── InterviewQuestions.java │ ├── LL.java │ ├── Main.java │ └── MergeSort.java ├── 19-stacks-n-queues/ │ ├── code/ │ │ ├── .idea/ │ │ │ ├── .gitignore │ │ │ ├── description.html │ │ │ ├── encodings.xml │ │ │ ├── misc.xml │ │ │ ├── modules.xml │ │ │ ├── project-template.xml │ │ │ ├── uiDesigner.xml │ │ │ └── vcs.xml │ │ ├── code.iml │ │ └── src/ │ │ └── com/ │ │ └── kunal/ │ │ ├── CircularQueue.java │ │ ├── CustomQueue.java │ │ ├── CustomStack.java │ │ ├── DynamicQueue.java │ │ ├── DynamicStack.java │ │ ├── InBuiltExamples.java │ │ ├── QueueMain.java │ │ ├── StackException.java │ │ └── StackMain.java │ └── questions/ │ ├── LargestAreaHistogram.java │ ├── QueueUsingStack.java │ ├── QueueUsingStackRemove.java │ ├── TwoStacks.java │ ├── ValidParenMinAdd.java │ └── ValidParenthesis.java ├── 20-trees/ │ └── code/ │ ├── AVL/ │ │ ├── .breakpoints │ │ ├── .cache/ │ │ │ └── replit/ │ │ │ ├── __replit_disk_meta.json │ │ │ ├── modules.stamp │ │ │ └── nix/ │ │ │ └── env.json │ │ ├── .classpath │ │ ├── .project │ │ ├── .replit │ │ ├── .settings/ │ │ │ ├── org.eclipse.jdt.apt.core.prefs │ │ │ ├── org.eclipse.jdt.core.prefs │ │ │ └── org.eclipse.m2e.core.prefs │ │ ├── .upm/ │ │ │ └── store.json │ │ ├── AVL.java │ │ └── Main.java │ ├── Advance questions/ │ │ ├── DoubleLinkedList.java │ │ ├── KthSmallest.java │ │ ├── KthSmallest2.java │ │ ├── Main.java │ │ ├── PreIn.java │ │ ├── TwoNodeSwap.java │ │ ├── TwoSum.java │ │ ├── VerticalTraversal.java │ │ └── WordLadder.java │ ├── Questions/ │ │ ├── .breakpoints │ │ ├── .cache/ │ │ │ └── replit/ │ │ │ ├── __replit_disk_meta.json │ │ │ ├── modules.stamp │ │ │ └── nix/ │ │ │ └── env.json │ │ ├── .classpath │ │ ├── .project │ │ ├── .replit │ │ ├── .settings/ │ │ │ ├── org.eclipse.jdt.apt.core.prefs │ │ │ ├── org.eclipse.jdt.core.prefs │ │ │ └── org.eclipse.m2e.core.prefs │ │ ├── .upm/ │ │ │ └── store.json │ │ ├── BFS.java │ │ ├── DFS.java │ │ ├── Main.java │ │ ├── PathSum.java │ │ └── SD.java │ ├── Segment trees/ │ │ ├── Main.java │ │ └── SegmentTree.java │ └── introduction/ │ ├── BST.java │ ├── BinaryTree.java │ └── Main.java ├── 21-StringBuffer/ │ └── code/ │ ├── Main.java │ └── RandomString.java ├── 22-large numbers/ │ └── code/ │ ├── Factorial.java │ └── Main.java ├── 23-file handling/ │ ├── code/ │ │ ├── Input.java │ │ ├── Main.java │ │ ├── Output.java │ │ ├── new-file.txt │ │ └── note.txt │ └── notes/ │ └── notes.txt ├── 24-heaps/ │ └── code/ │ └── heaps-1/ │ ├── Heap.java │ └── Main.java ├── 25-hashmaps/ │ └── code/ │ ├── Hashmaps introduction/ │ │ ├── HashMapFinal.java │ │ └── Main.java │ └── KarpRabin/ │ ├── KarpRabin.java │ └── Main.java ├── 26-advance-sorting/ │ ├── CountSort/ │ │ └── Main.java │ └── RadixSort/ │ └── Main.java ├── 27-huffman-coding/ │ └── code/ │ ├── Heap.java │ ├── HuffmanCoder.java │ └── Main.java └── 28-sqrt-decomposition/ └── code/ └── Main.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by https://www.toptal.com/developers/gitignore/api/macos,intellij,java # Edit at https://www.toptal.com/developers/gitignore?templates=macos,intellij,java ### Intellij ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff .idea/**/workspace.xml .idea/**/tasks.xml .idea/**/usage.statistics.xml .idea/**/dictionaries .idea/**/shelf # AWS User-specific .idea/**/aws.xml # Generated files .idea/**/contentModel.xml # Sensitive or high-churn files .idea/**/dataSources/ .idea/**/dataSources.ids .idea/**/dataSources.local.xml .idea/**/sqlDataSources.xml .idea/**/dynamic.xml .idea/**/uiDesigner.xml .idea/**/dbnavigator.xml # Gradle .idea/**/gradle.xml .idea/**/libraries # Gradle and Maven with auto-import # When using Gradle or Maven with auto-import, you should exclude module files, # since they will be recreated, and may cause churn. Uncomment if using # auto-import. # .idea/artifacts # .idea/compiler.xml # .idea/jarRepositories.xml # .idea/modules.xml # .idea/*.iml # .idea/modules # *.iml # *.ipr # CMake cmake-build-*/ # Mongo Explorer plugin .idea/**/mongoSettings.xml # File-based project format *.iws # IntelliJ out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Cursive Clojure plugin .idea/replstate.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties # Editor-based Rest Client .idea/httpRequests # Android studio 3.1+ serialized cache file .idea/caches/build_file_checksums.ser ### Intellij Patch ### # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 # *.iml # modules.xml # .idea/misc.xml # *.ipr # Sonarlint plugin # https://plugins.jetbrains.com/plugin/7973-sonarlint .idea/**/sonarlint/ # SonarQube Plugin # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin .idea/**/sonarIssues.xml # Markdown Navigator plugin # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced .idea/**/markdown-navigator.xml .idea/**/markdown-navigator-enh.xml .idea/**/markdown-navigator/ # Cache file creation bug # See https://youtrack.jetbrains.com/issue/JBR-2257 .idea/$CACHE_FILE$ # CodeStream plugin # https://plugins.jetbrains.com/plugin/12206-codestream .idea/codestream.xml ### Java ### # Compiled class file *.class # Log file *.log # BlueJ files *.ctxt # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.nar *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ### macOS ### # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # End of https://www.toptal.com/developers/gitignore/api/macos,intellij,java ================================================ FILE: README.md ================================================ # DSA + Interview preparation bootcamp - Subscribe to the [YouTube channel](https://www.youtube.com/KunalKushwaha?sub_confirmation=1) - [Lectures](https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ) - [Course website](https://www.techwithkunal.com/courses/dsa) - [Assignments](https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/tree/main/assignments) (solutions can be found on LeetCode) ================================================ FILE: SYLLABUS.md ================================================ - [Complete Git & GitHub Course](https://youtu.be/apGV9Kg7ics) - [Introduction to Programming](https://youtu.be/wn49bJOYAZM) - [Types of languages](https://youtu.be/wn49bJOYAZM?t=171) - [Memory management](https://youtu.be/wn49bJOYAZM?t=1488) - [Flow of the program](https://youtu.be/lhELGQAV4gg) - [Flowcharts](https://youtu.be/lhELGQAV4gg) - [Pseudocode](https://youtu.be/lhELGQAV4gg?t=715) - [Introduction to Java](https://youtu.be/4EP8YzcN0hQ) - [Introduction](https://youtu.be/4EP8YzcN0hQ) - [How it works](https://youtu.be/4EP8YzcN0hQ?t=93) - [Setup Installation](https://youtu.be/4EP8YzcN0hQ?t=1486) - [Input and Output in Java](https://youtu.be/TAtrPoaJ7gc) - [Conditionals & Loops in Java](https://youtu.be/ldYLYRNaucM?t=88) - [if-else](https://youtu.be/ldYLYRNaucM?t=88) - [loops](https://youtu.be/ldYLYRNaucM?t=440) - [Switch statements](https://youtu.be/mA23x39DjbI) - [Data-types](https://youtu.be/TAtrPoaJ7gc?t=2800) - [Coding best practices](https://youtu.be/waGfV-IoOt8) - [Functions](https://youtu.be/vvanI8NRlSI) - [Introduction](https://youtu.be/vvanI8NRlSI) - [Scoping in Java](https://youtu.be/vvanI8NRlSI?t=2801) - [Shadowing](https://youtu.be/vvanI8NRlSI?t=3584) - [Variable Length Arguments](https://youtu.be/vvanI8NRlSI?t=4013) - [Overloading](https://youtu.be/vvanI8NRlSI?t=4327) - [Arrays](https://youtu.be/n60Dn0UsbEk) - [Introduction](https://youtu.be/n60Dn0UsbEk) - [Memory management](https://youtu.be/n60Dn0UsbEk?t=632) - [Input and Output](https://youtu.be/n60Dn0UsbEk?t=1675) - [ArrayList Introduction](https://youtu.be/n60Dn0UsbEk?t=4868) - Searching - [Linear Search](https://youtu.be/_HRA37X8N_Q) - [Binary Search](https://youtu.be/f6UU7V3szVw) - [Modified Binary Search](https://youtu.be/f6UU7V3szVw?t=2508) - [Binary Search on 2D Arrays](https://www.youtube.com/watch?v=enI_KyGLYPo) - Sorting - [Insertion Sort](https://youtu.be/By_5-RRqVeE) - [Selection Sort](https://youtu.be/Nd4SCCIHFWk) - [Bubble Sort](https://youtu.be/F5MZyqRp_IM) - [Cyclic Sort](https://youtu.be/JfinxytTYFQ) - [Count Sort](https://youtu.be/FOo820lJV1Y) - [Radix Sort](https://youtu.be/mLi6VQDqAOs) - [Pattern questions](https://youtu.be/lsOOs5J8ycw) - [Strings](https://www.youtube.com/watch?v=zL1DPZ0Ovlo) - [Introduction](https://www.youtube.com/watch?v=zL1DPZ0Ovlo) - [How Strings work](https://youtu.be/zL1DPZ0Ovlo?t=216) - [Comparison of methods](https://youtu.be/zL1DPZ0Ovlo?t=977) - [Operations in Strings](https://youtu.be/zL1DPZ0Ovlo?t=1681) - [StringBuilder in Java](https://youtu.be/zL1DPZ0Ovlo?t=4199) - [StringBuffer](https://www.youtube.com/watch?v=YFZai3fPUQI) - [Maths for DSA](https://youtu.be/fzip9Aml6og) - [Introduction](https://youtu.be/fzip9Aml6og?t=20) - [Complete Bitwise Operators](https://youtu.be/fzip9Aml6og?t=95) - [Range of numbers](https://youtu.be/fzip9Aml6og?t=4169) - [Prime numbers](https://youtu.be/lmSpZ0bjCyQ?t=57) - [Sieve of Eratosthenes](https://youtu.be/lmSpZ0bjCyQ?t=850) - [Newton's Square Root Method](https://youtu.be/lmSpZ0bjCyQ?t=1989) - [Factors](https://youtu.be/lmSpZ0bjCyQ?t=3004) - [Modulo properties](https://youtu.be/lmSpZ0bjCyQ?t=3980) - [Number Theory](https://youtu.be/lmSpZ0bjCyQ?t=4405) - [HCF / LCM](https://youtu.be/lmSpZ0bjCyQ?t=5110) - [Euclidean algorithm](https://youtu.be/lmSpZ0bjCyQ?t=5520) - [BigInteger & BigDecimal](https://www.youtube.com/watch?v=lHtoypC-4Ps) - [Recursion](https://www.youtube.com/playlist?list=PL9gnSGHSqcnp39cTyB1dTZ2pJ04Xmdrod) - [Introduction](https://youtu.be/M2uO2nMT0Bk) - [Flow of recursive programs - stacks](https://youtu.be/M2uO2nMT0Bk?t=2124) - [Why recursion?](https://youtu.be/M2uO2nMT0Bk?t=2708) - [Tree building of function calls](https://youtu.be/M2uO2nMT0Bk?t=3033) - [Tail recursion](https://youtu.be/M2uO2nMT0Bk?t=4308) - [Sorting](https://www.youtube.com/playlist?list=PL9gnSGHSqcnq-9CXLt9DsInytRMLoyZQ_) - [Merge Sort](https://youtu.be/iKGAgWdgoRk) - [Quick Sort](https://www.youtube.com/watch?v=Z8svOqamag8&list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ&index=27) - [Backtracking](https://youtu.be/zg5v2rlV1tM) - [N-Queens](https://youtu.be/nC1rbW2YSz0) - [N-Knights](https://youtu.be/nC1rbW2YSz0?t=2342) - [Sudoku Solver](https://youtu.be/nC1rbW2YSz0?t=3190) - [Maze problems](https://www.youtube.com/watch?v=zg5v2rlV1tM) - [Recursion String Problems](https://youtu.be/gdifkIwCJyg) - [Recursion Google, Amazon Questions](https://youtu.be/9ByWqPzfXDU) - [Recursion Array Problems](https://youtu.be/sTdiMLom00U) - [Recursion Pattern Problems](https://youtu.be/ymgnIIclCF0) - [Subset Questions](https://youtu.be/9ByWqPzfXDU) - [Space and Time Complexity Analysis](https://youtu.be/mV3wrLBbuuE) - [Introduction](https://youtu.be/mV3wrLBbuuE) - [Comparisons of various cases](https://youtu.be/mV3wrLBbuuE?t=1039) - [Solving Linear Recurrence Relations](https://youtu.be/mV3wrLBbuuE?t=6252) - [Solving Divide and Conquer Recurrence Relations](https://youtu.be/mV3wrLBbuuE?t=4609) - [Big-O, Big-Omega, Big-Theta Notations](https://youtu.be/mV3wrLBbuuE?t=2271) - [Little Notations](https://youtu.be/mV3wrLBbuuE?t=2960) - [Get equation of any relation easily - best and easiest approach](https://youtu.be/mV3wrLBbuuE?t=8189) - [Complexity discussion of all the problems we do](https://youtu.be/mV3wrLBbuuE?t=3866) - [Space Complexity](https://youtu.be/mV3wrLBbuuE?t=3330) - [NP-Completeness Introduction](https://youtu.be/mV3wrLBbuuE?t=8695) - [Object Oriented Programming](https://www.youtube.com/playlist?list=PL9gnSGHSqcno1G3XjUbwzXHL8_EttOuKk) - [Introduction](https://www.youtube.com/watch?v=BSVKUk58K6U) - [Classes & its instances](https://youtu.be/BSVKUk58K6U?t=467) - [this keyword in Java](https://youtu.be/BSVKUk58K6U?t=3380) - [Properties](https://www.youtube.com/watch?v=46T2wD3IuhM) - [Inheritance](https://youtu.be/46T2wD3IuhM?t=146) - [Abstraction](https://youtu.be/46T2wD3IuhM?t=7102) - [Polymorphism](https://youtu.be/46T2wD3IuhM?t=4226) - [Encapsulation](https://youtu.be/46T2wD3IuhM?t=7022) - [Overloading & Overriding](https://youtu.be/46T2wD3IuhM?t=4834) - [Static & Non-Static](https://youtu.be/_Ya6CN13t8k?t=1137) - [Packages](https://youtu.be/_Ya6CN13t8k?t=182) - [Access Control](https://youtu.be/W145DXs8fFg) - [Interfaces](https://youtu.be/rgHZa7-Dibg?t=1510) - [Abstract Classes](https://youtu.be/rgHZa7-Dibg?t=68) - [Annotations](https://youtu.be/rgHZa7-Dibg?t=3438) - [Singleton Class](https://youtu.be/_Ya6CN13t8k?t=4240) - [final, finalize, finally](https://youtu.be/46T2wD3IuhM?t=6317) - [Object Cloning](https://youtu.be/OY2lPr8h93U?t=4352) - [Object Class](https://youtu.be/W145DXs8fFg?t=1943) - [Generics](https://www.youtube.com/watch?v=OY2lPr8h93U) - [Exception Handling](https://youtu.be/OY2lPr8h93U?t=3405) - [Collections Framework](https://youtu.be/9ogGan-R1pc?t=49) - [Vector Class](https://youtu.be/9ogGan-R1pc?t=668) - [Lambda Expression](https://youtu.be/OY2lPr8h93U?t=2894) - [Enums](https://youtu.be/9ogGan-R1pc?t=909) - Linked List - [Introduction](https://youtu.be/58YbpRDc4yw) - [Singly + Doubly + Circular LinkedList](https://youtu.be/58YbpRDc4yw) - [Fast and slow pointer](https://youtu.be/70tx7KcMROc) - [Cycle Detection](https://youtu.be/70tx7KcMROc) - [Reversal of LinkedList](https://youtu.be/70tx7KcMROc) - [Linked List + Recursion](https://youtu.be/70tx7KcMROc) - [Stacks & Queues](https://www.youtube.com/watch?v=rHQI4mrJ3cg) - Introduction - Push efficient - Pop efficient - Queue using Stack and vice versa - Circular Queue - [Interview problems](https://www.youtube.com/watch?v=S9LUYztYLu4) - [File handling](https://www.youtube.com/watch?v=b35mlSPOlJg) - [Trees](https://www.youtube.com/playlist?list=PL9gnSGHSqcnqfctdbCQKaw5oZ9Up2cmsq) - [Introduction](https://www.youtube.com/watch?v=4s1Tcvm00pA) - Binary Trees - Binary Search Trees - [Interview questions](https://www.youtube.com/watch?v=9D-vP-jcc-Y) - DFS - BFS - [AVL Trees](https://www.youtube.com/watch?v=CVA85JuJEn0) - [Segment Tree](https://www.youtube.com/watch?v=ciHThtTVNto) - Fenwick Tree / Binary Indexed Tree - Heaps - [Introduction](https://youtu.be/Qf-TDPr0nYw) - Theory - Priority Queue - Heapsort - Two Heaps Method - k-way merge - Top k elements - Interval problems - HashMap - [Introduction](https://youtu.be/XLbvmMz8Fr8) - Theory - how it works - Comparisons of various forms - Limitations and how to solve - Map using LinkedList - Map using Hash - Chaining - Probing - [Huffman Coding](https://youtu.be/XLfgeaYHinM) - [Karp-Rabin Strng matching algorithm](https://youtu.be/swciWFPq3NE) - Subarray Questions: Sliding window, Two Pointer, Kadane's Algorithm - Graphs - Introduction - BFS - DFS - Working with graph components - Minimum Spanning Trees - Kruskal Algorithm - Prims Algorithm - Dijkstra’s shortest path algorithm - Topological Sort - Bellman ford - A* pathfinding Algorithm - Dynamic Programming - Introduction - Recursion + Recursion DP + Iteration + Iteration Space Optimized - Complexity Analysis - 0/1 Knapsack - Subset Questions - Unbounded Knapsack - Subsequence questions - String DP - Greedy Algorithms - Tries ### Advanced concepts apart from interviews - Bitwise + DP - Extended Euclidean algorithm - Modulo Multiplicative Inverse - Linear Diophantine Equations - Matrix Exponentiation - Mathematical Expectation - Catalan Numbers - Fermat’s Theorem - Wilson's Theorem - Euler's Theorem - Lucas Theorem - Chinese Remainder Theorem - Euler Totient - NP-Completeness - Multithreading - Square Root Decomposition ================================================ FILE: assignments/01-flow-of-program.md ================================================ [Video Link](https://youtu.be/lhELGQAV4gg) ## Create flowchart and pseudocode for the following: 1. Input a year and find whether it is a leap year or not. 2. Take two numbers and print the sum of both. 3. Take a number as input and print the multiplication table for it. 4. Take 2 numbers as inputs and find their HCF and LCM. 5. Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all. ================================================ FILE: assignments/02-first-java.md ================================================ # [Video Link](https://youtu.be/TAtrPoaJ7gc) ## Write Java programs for the following: 1. Write a program to print whether a number is even or odd, also take input from the user. 2. Take name as input and print a greeting message for that particular name. 3. Write a program to input principal, time, and rate (P, T, R) from the user and find Simple Interest. 4. Take in two numbers and an operator (+, -, *, /) and calculate the value. (Use if conditions) 5. Take 2 numbers as input and print the largest number. 6. Input currency in rupees and output in USD. 7. To calculate Fibonacci Series up to n numbers. 8. To find out whether the given String is Palindrome or not. 9. To find Armstrong Number between two given number. ================================================ FILE: assignments/03-conditionals-loops.md ================================================ # [Video Link](https://youtu.be/ldYLYRNaucM) ## Write Java programs for the following: ### Basic Java Programs 1. Area Of Circle Java Program 2. Area Of Triangle 3. Area Of Rectangle Program 4. Area Of Isosceles Triangle 5. Area Of Parallelogram 6. Area Of Rhombus 7. Area Of Equilateral Triangle 8. Perimeter Of Circle 9. Perimeter Of Equilateral Triangle 10. Perimeter Of Parallelogram 11. Perimeter Of Rectangle 12. Perimeter Of Square 13. Perimeter Of Rhombus 14. Volume Of Cone Java Program 15. Volume Of Prism 16. Volume Of Cylinder 17. Volume Of Sphere 18. Volume Of Pyramid 19. Curved Surface Area Of Cylinder 20. Total Surface Area Of Cube 21. Fibonacci Series In Java Programs 22. [Subtract the Product and Sum of Digits of an Integer](https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/) 23. Input a number and print all the factors of that number (use loops). 24. Take integer inputs till the user enters 0 and print the sum of all numbers (HINT: while loop) 25. Take integer inputs till the user enters 0 and print the largest number from all. 26. Addition Of Two Numbers ### Intermediate Java Programs 1. Factorial Program In Java 2. Calculate Electricity Bill 3. Calculate Average Of N Numbers 4. Calculate Discount Of Product 5. Calculate Distance Between Two Points 6. Calculate Commission Percentage 7. Power In Java 8. Calculate Depreciation of Value 9. Calculate Batting Average 10. Calculate CGPA Java Program 11. Compound Interest Java Program 12. Calculate Average Marks 13. Sum Of N Numbers 14. Armstrong Number In Java 15. Find Ncr & Npr 16. Reverse A String In Java 17. Find if a number is palindrome or not 18. Future Investment Value 19. HCF Of Two Numbers Program 20. LCM Of Two Numbers 21. Java Program Vowel Or Consonant 22. Perfect Number In Java 23. Check Leap Year Or Not 24. Sum Of A Digits Of Number 25. Kunal is allowed to go out with his friends only on the even days of a given month. Write a program to count the number of days he can go out in the month of August. 26. Write a program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero. ================================================ FILE: assignments/04-functions.md ================================================ # [Video Link](https://youtu.be/vvanI8NRlSI) 1. [Define two methods to print the maximum and the minimum number respectively among three numbers entered by the user.](https://www.java67.com/2019/05/how-to-find-largest-and-smallest-of-three-numbers-in-java.html) 2. [Define a program to find out whether a given number is even or odd.](https://www.geeksforgeeks.org/java-program-to-check-if-a-given-integer-is-odd-or-even/) 3. [A person is eligible to vote if his/her age is greater than or equal to 18. Define a method to find out if he/she is eligible to vote.](https://www.efaculty.in/java-programs/voting-age-program-in-java/) 4. [Write a program to print the sum of two numbers entered by user by defining your own method.](https://code4coding.com/addition-of-two-numbers-in-java-using-method/) 5. [Define a method that returns the product of two numbers entered by user.](https://code4coding.com/java-program-to-multiply-two-numbers-using-method/) 6. [Write a program to print the circumference and area of a circle of radius entered by user by defining your own method.](https://beginnersbook.com/2014/01/java-program-to-calculate-area-and-circumference-of-circle/) 7. [Define a method to find out if a number is prime or not.](https://www.geeksforgeeks.org/java-program-to-check-if-a-number-is-prime-or-not/) 8. [Write a program that will ask the user to enter his/her marks (out of 100). Define a method that will display grades according to the marks entered as below:](https://www.techcrashcourse.com/2017/02/java-program-to-calculate-grade-of-students.html)
 
Marks        Grade 
91-100         AA 
81-90          AB 
71-80          BB 
61-70          BC 
51-60          CD 
41-50          DD 
<=40          Fail 
9. [Write a program to print the factorial of a number by defining a method named 'Factorial'.](https://www.javatpoint.com/factorial-program-in-java) Factorial of any number n is represented by n! and is equal to 1 * 2 * 3 * .... * (n-1) *n. E.g.-
4! = 1 * 2 * 3 * 4 = 24 
3! = 3 * 2 * 1 = 6 
2! = 2 * 1 = 2 
Also, 
1! = 1 
0! = 1
10. [Write a function to find if a number is a palindrome or not. Take number as parameter.](https://www.geeksforgeeks.org/check-if-a-number-is-palindrome/) 11. Convert the programs in [flow of program](01-flow-of-program.md), [first java](02-first-java.md), [conditionals & loops](03-conditionals-loops.md) assignments into functions. 12. [Write a function to check if a given triplet is a Pythagorean triplet or not.](https://www.geeksforgeeks.org/find-pythagorean-triplet-in-an-unsorted-array/) (A Pythagorean triplet is when the sum of the square of two numbers is equal to the square of the third number). 13. [Write a function that returns all prime numbers between two given numbers.](https://www.geeksforgeeks.org/program-to-find-prime-numbers-between-given-interval/) 14. [Write a function that returns the sum of first n natural numbers.](https://www.geeksforgeeks.org/program-find-sum-first-n-natural-numbers/) ================================================ FILE: assignments/05-arrays.md ================================================ # [Video Link](https://youtu.be/n60Dn0UsbEk) ## Submit the following on your Leetcode profile itself. ### Easy 1. [Build Array from Permutation](https://leetcode.com/problems/build-array-from-permutation/) 2. [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) 3. [Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/) 4. [Richest Customer Wealth](https://leetcode.com/problems/richest-customer-wealth/) 5. [Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) 6. [Kids With the Greatest Number of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/) 7. [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/) 8. [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) 9. [Create Target Array in the Given Order](https://leetcode.com/problems/create-target-array-in-the-given-order/) 10. [Check if the Sentence Is Pangram](https://leetcode.com/problems/check-if-the-sentence-is-pangram/) 11. [Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule/) 12. [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude/) 13. [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) 14. [Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/) 15. [Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/) 16. [Find Numbers with Even Number of Digits](https://leetcode.com/problems/find-numbers-with-even-number-of-digits/) 17. [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) 18. [Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/) 19. [Maximum Population Year](https://leetcode.com/problems/maximum-population-year/) 20. [Determine Whether Matrix Can Be Obtained By Rotation](https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/) 21. [Two Sum](https://leetcode.com/problems/two-sum/) 22. [Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) 23. [Lucky Number In a Matrix](https://leetcode.com/problems/lucky-numbers-in-a-matrix/) 24. [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) 25. [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) 26. [Plus One](https://leetcode.com/problems/plus-one/) 27. [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) 28. [Minimum Cost to Move Chips to The Same Position](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/) ### Medium 1. [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) 2. [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) 3. [Spiral Matrix III](https://leetcode.com/problems/spiral-matrix-iii/) 4. [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) 5. [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) 6. [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) 7. [Jump Game](https://leetcode.com/problems/jump-game/) 8. [Rotate Array](https://leetcode.com/problems/rotate-array/) 9. [Sort Colors](https://leetcode.com/problems/sort-colors/) 10. [House Robber](https://leetcode.com/problems/house-robber/) ### Hard 1. [Max Value of Equation](https://leetcode.com/problems/max-value-of-equation/) 2. [First Missing Positive](https://leetcode.com/problems/first-missing-positive/) 3. [Good Array](https://leetcode.com/problems/check-if-it-is-a-good-array/) ================================================ FILE: assignments/06-searching.md ================================================ # Videos: - [Linear Search](https://youtu.be/_HRA37X8N_Q) - [Binary Search](https://youtu.be/f6UU7V3szVw) - [Binary Search Questions](https://youtu.be/W9QJ8HaRvJQ) - [Binary Search in 2D Arrays](https://youtu.be/enI_KyGLYPo) # Problems: ## Easy - [Square Root](https://leetcode.com/problems/sqrtx/) - [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/) - [First Bad Version](https://leetcode.com/problems/first-bad-version/) - [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) - [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) - [Arranging Coins(Easy)](https://leetcode.com/problems/arranging-coins/) - [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) - [Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/) - [Search Insert Position](https://leetcode.com/problems/search-insert-position/) - [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) - [Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/) - [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) - [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) - [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap/) - [Check If N and Its Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist/) - [Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/) - [Binary Search](https://leetcode.com/problems/binary-search/) ## Medium - [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) - [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) - [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) - [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) - [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) - [Find Peak Element](https://leetcode.com/problems/find-peak-element/) - [Find Right Interval](https://leetcode.com/problems/find-right-interval/) - [Reach a Number](https://leetcode.com/problems/reach-a-number/) - [Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/) - [Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) - [Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference/) - [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) - [Find a Peak Element II](https://leetcode.com/problems/find-a-peak-element-ii/) - [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) - [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) - [Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) - [4 Sum](https://leetcode.com/problems/4sum/) ## Hard - [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) - [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) - [Aggressive cows](https://www.spoj.com/problems/AGGRCOW/) - [Book allocation](https://www.geeksforgeeks.org/allocate-minimum-number-pages/) - [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) - [Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array/) - [Count smaller number after Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) - [Divide Chocolate Problem](https://curiouschild.github.io/leetcode/2019/06/21/divide-chocolate.html) ================================================ FILE: assignments/07-sorting.md ================================================ # Videos - [Bubble Sort](https://youtu.be/F5MZyqRp_IM) - [Selection Sort](https://youtu.be/Nd4SCCIHFWk) - [Insertion Sort](https://youtu.be/By_5-RRqVeE) - [Cycle Sort](https://www.youtube.com/watch?v=JfinxytTYFQ&list=RDCMUCBGOUQHNNtNGcGzVq5rIXjw&start_radio=1&rv=JfinxytTYFQ&t=2) - [Merge Sort](https://youtu.be/iKGAgWdgoRk) - [Quick Sort](https://youtu.be/Z8svOqamag8) # Questions ## Easy - [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) - [Majority Element](https://leetcode.com/problems/majority-element/) - [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) - [Missing Number](https://leetcode.com/problems/missing-number/) - [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) - [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) - [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) - [Assign Cookies](https://leetcode.com/problems/assign-cookies/) - [Array Partition I](https://leetcode.com/problems/array-partition-i/) - [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) - [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) - [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) - [Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/) - [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) - [Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/) - [Height Checker](https://leetcode.com/problems/height-checker/) - [Relative Sort Array](https://leetcode.com/problems/relative-sort-array/) - [Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference/) - [Rank Transform of an Array](https://leetcode.com/problems/rank-transform-of-an-array/) - [Sort Integers by The Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/) - [How Many Numbers Are Smaller Than the Current Number](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/) - [Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/) - [Average Salary Excluding the Minimum and Maximum Salary](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/) - [Make Two Arrays Equal by Reversing Sub-arrays](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/) - [Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/) - [Sort Array by Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency/) - [Special Array With X Elements Greater Than or Equal X](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/) - [Find all numbers disappeared in an array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) - [Set Mismatch](https://leetcode.com/problems/set-mismatch/) - [2Sum](https://leetcode.com/problems/two-sum/) ## Medium - [3Sum](https://leetcode.com/problems/3sum/) - [3Sum Closest](https://leetcode.com/problems/3sum-closest/) - [4Sum](https://leetcode.com/problems/4sum/) - [Group Anagrams](https://leetcode.com/problems/group-anagrams/) - [Merge Intervals](https://leetcode.com/problems/merge-intervals/) - [Sort Colors](https://leetcode.com/problems/sort-colors/) - [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) - [Sort List](https://leetcode.com/problems/sort-list/) - [Largest Number](https://leetcode.com/problems/largest-number/) - [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) - [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) - [Find all Duplicates in an array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) ## Hard - [First missing Positive](https://leetcode.com/problems/first-missing-positive/) ================================================ FILE: assignments/08-strings.md ================================================ # [Video Link](https://youtu.be/zL1DPZ0Ovlo) # Problems ## Easy - [Defanging an Ip address](https://leetcode.com/problems/defanging-an-ip-address/) - [Shuffle String](https://leetcode.com/problems/shuffle-string/) - [Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/) - [Count Items Matching a rule](https://leetcode.com/problems/count-items-matching-a-rule/) - [Sorting the Sentence](https://leetcode.com/problems/sorting-the-sentence/) - [Check if two strings are equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/) - [To Lower Case](https://leetcode.com/problems/to-lower-case/) - [Determine if string halves are alike](https://leetcode.com/problems/determine-if-string-halves-are-alike/) - [Decrypt String from Alphabet to Integer Mapping](https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/) - [Number of Strings That Appear as Substrings in Word](https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/) - [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin/) - [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) - [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) - [Implement strStr()](https://leetcode.com/problems/implement-strstr/) - [Long Pressed Name](https://leetcode.com/problems/long-pressed-name/) - [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) - [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) - [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) - [Maximum Repeating Substring](https://leetcode.com/problems/maximum-repeating-substring/) - [Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/) - [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) - [Reverse Prefix of Word](https://leetcode.com/problems/reverse-prefix-of-word/) - [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) - [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) - [Length of last word](https://leetcode.com/problems/length-of-last-word/) ## Medium - [Jump Game VII](https://leetcode.com/problems/jump-game-vii/) - [Split Two Strings to Make Palindrome](https://leetcode.com/problems/split-two-strings-to-make-palindrome/) - [Number of Ways to Split a String](https://leetcode.com/problems/number-of-ways-to-split-a-string/) - [Sentence Similarity III](https://leetcode.com/problems/sentence-similarity-iii/) - [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) - [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) - [Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters/) - [Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string/) - [Multiply Strings](https://leetcode.com/problems/multiply-strings/) - [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) - [Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/) - [Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/) - [Count Number of Homogenous Substrings](https://leetcode.com/problems/count-number-of-homogenous-substrings/) - [Get Equal Substrings Within Budget](https://leetcode.com/problems/get-equal-substrings-within-budget/) - [Shifting Letters](https://leetcode.com/problems/shifting-letters/) - [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) - [Find Kth Bit in Nth Binary String](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) - [Camelcase Matching](https://leetcode.com/problems/camelcase-matching/) - [Print Words Vertically](https://leetcode.com/problems/print-words-vertically/) ## Hard - [Valid Number](https://leetcode.com/problems/valid-number/) - [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) - [Last Substring in Lexicographical Order](https://leetcode.com/problems/last-substring-in-lexicographical-order/) - [Basic Calculator](https://leetcode.com/problems/basic-calculator/) - [Minimum Number of Operations to Make String Sorted](https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/) - [Check If String Is Transformable With Substring Sort Operations](https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/) - [Orderly Queue](https://leetcode.com/problems/orderly-queue/) - [Special Binary String](https://leetcode.com/problems/special-binary-string/) # Additionally - [Click "Show problem tags" and do questions that have tags for things we have learnt so far only.](https://leetcode.com/tag/string/) ================================================ FILE: assignments/09-patterns.md ================================================ Pattern Questions Print these patterns using loops: ```text 1. ***** ***** ***** ***** ***** 2. * ** *** **** ***** 3. ***** **** *** ** * 4. 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 5. * ** *** **** ***** **** *** ** * 6. * ** *** **** ***** 7. ***** **** *** ** * 8. * *** ***** ******* ********* 9. ********* ******* ***** *** * 10. * * * * * * * * * * * * * * * 11. * * * * * * * * * * * * * * * 12. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 13. * * * * * * * ********* 14. ********* * * * * * * * 15. * * * * * * * * * * * * * * * * 16. 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 17. 1 212 32123 4321234 32123 212 1 18. ********** **** **** *** *** ** ** * * * * ** ** *** *** **** **** ********** 19. * * ** ** *** *** **** **** ********** **** **** *** *** ** ** * * 20. **** * * * * * * **** 21. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 22. 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 23. * * * * * * * * * 24. * * ** ** * * * * * * * * * ** * * ** * * * * * * * * * ** ** * * 25. ***** * * * * * * ***** 26. 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6 27. 1 2 3 4 17 18 19 20 5 6 7 14 15 16 8 9 12 13 10 11 28. * * * * * * * * * * * * * * * * * * * * * * * * * 29. * * ** ** *** *** **** **** ********** **** **** *** *** ** ** * * 30. 1 2 1 2 3 2 1 2 3 4 3 2 1 2 3 4 5 4 3 2 1 2 3 4 5 31. 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 32. E D E C D E B C D E A B C D E 33. a B c D e F g H i J k L m N o 34. E D C B A D C B A C B A B A A 35. 1 1 12 21 123 321 12344321 ``` ================================================ FILE: assignments/10-recursion.md ================================================ # Videos - [Complete Recursion Course](https://www.youtube.com/playlist?list=PL9gnSGHSqcnp39cTyB1dTZ2pJ04Xmdrod) # Problems ## Easy - [Sum Triangle from Array](https://www.geeksforgeeks.org/sum-triangle-from-array/) `GFG` - [Maximum and Minimum value in an array](https://www.geeksforgeeks.org/recursive-programs-to-find-minimum-and-maximum-elements-of-array/) `GFG` - [Binary Search using recursion](https://leetcode.com/problems/binary-search/) `leetcode` - [First Uppercase Letter in a String](https://www.geeksforgeeks.org/first-uppercase-letter-in-a-string-iterative-and-recursive/) `GFG` - [Reverse String](https://leetcode.com/problems/reverse-string/) `leetcode` - [Print 1 To N Without Loop](https://practice.geeksforgeeks.org/problems/print-1-to-n-without-using-loops-1587115620/1/) `GFG` - [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) `leetcode` - [Special Fibonacci](https://www.codechef.com/problems/FIBXOR01/) `CodeChef` - [Length of string using Recursion](https://www.geeksforgeeks.org/program-for-length-of-a-string-using-recursion/) `GFG` - [Geek-onacci Number](https://practice.geeksforgeeks.org/problems/geek-onacci-number/0/) `GFG` - [Recursive Bubble Sort](https://www.geeksforgeeks.org/recursive-bubble-sort/) `GFG` - [Recursive Insertion Sort](https://www.geeksforgeeks.org/recursive-insertion-sort/) `GFG` - [Sum of digit of a number using Recursion](https://www.geeksforgeeks.org/sum-digit-number-using-recursion/) `GFG` - [Product of two numbers using Recursion](https://www.geeksforgeeks.org/product-2-numbers-using-recursion/) `GFG` - [Check Prime or not](https://www.geeksforgeeks.org/recursive-program-prime-number/) `GFG` - [Sum of Natural numbers using Recursion](https://www.geeksforgeeks.org/sum-of-natural-numbers-using-recursion/) `GFG` - [Power of Two](https://leetcode.com/problems/power-of-two/) `leetcode` - [Power of Three](https://leetcode.com/problems/power-of-three/) `leetcode` - [Power of Four](https://leetcode.com/problems/power-of-four/) `leetcode` - Write a recursive function for given n and a to determine x: ```java n = a ^ x a = 2, 3, 4 (2 ^ -31) <= n <= (2 ^ 31) - 1 ``` - [Write a recursive function that returns the factorial of a number.](https://www.hackerrank.com/challenges/30-recursion/problem) `HackerRank` - [Write a recursive function to check whether an array is sorted or not.](https://www.geeksforgeeks.org/program-check-array-sorted-not-iterative-recursive) `GFG` - [Number of Steps to Reduce a Number to Zero.](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) `leetcode` - [Check for balanced paranthesis using recursion without stack.](https://www.geeksforgeeks.org/check-for-balanced-parenthesis-without-using-stack/) `GFG` - [Remove consecutive duplicate characters from a string.](https://www.geeksforgeeks.org/remove-consecutive-duplicates-string/) `GFG` - [Print all possible palindromic partitions of a string.](https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/) `GFG` - [Power Set of permutations of a string in Lexicographic order.](https://www.geeksforgeeks.org/powet-set-lexicographic-order/) `GFG` ## Medium - [Combination Sum](https://leetcode.com/problems/combination-sum/) `leetcode` - [Word Search](https://leetcode.com/problems/word-search/) `leetcode` - [Target sum](https://leetcode.com/problems/target-sum/) `leetcode` - [Find Kth Bit in Nth Binary String](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) `leetcode` - [K-th Symbol in Grammar](https://leetcode.com/problems/k-th-symbol-in-grammar/) `leetcode` - [Count Good Numbers](https://leetcode.com/problems/count-good-numbers/) `leetcode` - [N Digit numbers with digits in increasing order](https://practice.geeksforgeeks.org/problems/n-digit-numbers-with-digits-in-increasing-order5903/1/) `GFG` - [Pow(x, n)](https://leetcode.com/problems/powx-n/) `leetcode` - [Minimum Non-Zero Product of the Array Elements](https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/) `leetcode` - [Handshakes](https://practice.geeksforgeeks.org/problems/handshakes1303/1/) `GFG` - [HackerRank](https://www.hackerrank.com/domains/algorithms?filters%5Bsubdomains%5D%5B%5D=recursion&filters%5Bdifficulty%5D%5B%5D=medium) - [Divisible Subset](https://www.codechef.com/problems/DIVSUBS) `Codechef` - [Perfect squares](https://leetcode.com/problems/perfect-squares/)`leetcode` - [decode string](https://leetcode.com/problems/decode-string/)`leetcode` - [find the winner of the circular game](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) `leetcode` - [Different ways to add parantheses in the expression](https://leetcode.com/problems/different-ways-to-add-parentheses/) `leetcode` - [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) `leetcode` - [Predict the winner.](https://leetcode.com/problems/predict-the-winner/) `leetcode` - [Gray code](https://practice.geeksforgeeks.org/problems/gray-code-1611215248/1/) `GFG` `Google` - [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) `leetcode` - [combination Sum III](https://leetcode.com/problems/combination-sum-iii/) `leetcode` - [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) `leetcode` - [Letter tile possibilities](https://leetcode.com/problems/letter-tile-possibilities/) `leetcode` - [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) `leetcode` - [Sort a stack using recursion](https://www.geeksforgeeks.org/sort-a-stack-using-recursion/) `GFG` - [Reverse a stack using recursion](https://www.geeksforgeeks.org/reverse-a-stack-using-recursion/) `GFG` - [Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) `leetcode` - [Lowest Common Ancestor of a Binary Tree](https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1/) `GFG` `Amex` - [Prime numbers after prime P with sum S](https://www.geeksforgeeks.org/prime-numbers-after-prime-p-with-sum-s/) `GFG` - [Path with Maximum Gold](https://leetcode.com/problems/path-with-maximum-gold/) `leetcode` - [Longest Possible Route in a Matrix with Hurdles](https://www.geeksforgeeks.org/longest-possible-route-in-a-matrix-with-hurdles/) `GFG` - [Tug of war](https://www.geeksforgeeks.org/tug-of-war/) `GFG` `Adobe` - [Rat in a maze](https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/) `GFG` - [Reorder List](https://leetcode.com/problems/reorder-list/) `leetcode` ## Hard - [Parsing A Boolean Expression](https://leetcode.com/problems/parsing-a-boolean-expression/) `leetcode` - [Special Binary String](https://leetcode.com/problems/special-binary-string/) `leetcode` - [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) `leetcode` - [Next Happy Number](https://practice.geeksforgeeks.org/problems/next-happy-number4538/1/) `GFG` - [Basic Calculator](https://leetcode.com/problems/basic-calculator/) `leetcode` - [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) `leetcode` - [Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors/) `leetcode` - [N Queens](https://leetcode.com/problems/n-queens/) `leetcode` - [N Queens II](https://leetcode.com/problems/n-queens-ii/) `leetcode` - [Word break II](https://leetcode.com/problems/word-break-ii/) `leetcode` `Google` - [Unique paths III](https://leetcode.com/problems/unique-paths-iii/) `leetcode` - [Find shortest safe route in a path with landmines](https://www.geeksforgeeks.org/find-shortest-safe-route-in-a-path-with-landmines/) `GFG` `Google` - [Minimum steps to destination](https://practice.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1/) `GFG` `Amex` `Adobe` - [Hamiltonian Cycle](https://www.geeksforgeeks.org/hamiltonian-cycle-backtracking-6/) `GFG` - [M colorning problem](https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/) `GFG` - [The Knight's tour](https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/) `GFG` - [Maximum number possible by doing at-most K swaps](https://www.geeksforgeeks.org/find-maximum-number-possible-by-doing-at-most-k-swaps/) `GFG` - [HackerRank](https://www.hackerrank.com/domains/algorithms?filters%5Bsubdomains%5D%5B%5D=recursion&filters%5Bdifficulty%5D%5B%5D=hard) - [Concatenated Words](https://leetcode.com/problems/concatenated-words/)`leetcode` ================================================ FILE: assignments/11-bitwise.md ================================================ # [Video link](https://youtu.be/fzip9Aml6og) ## Problems ## Easy - [Add Binary](https://leetcode.com/problems/add-binary/) - [Single Number](https://leetcode.com/problems/single-number/) - [Reverse Bits](https://leetcode.com/problems/reverse-bits/) - [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) - [Counting Bits](https://leetcode.com/problems/counting-bits/) - [Binary Watch](https://leetcode.com/problems/binary-watch/) - [Hamming Distance](https://leetcode.com/problems/hamming-distance/) - [Number Complement](https://leetcode.com/problems/number-complement/) - [Set Mismatch](https://leetcode.com/problems/set-mismatch/) - [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/) - [Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/) - [Binary Gap](https://leetcode.com/problems/binary-gap/) - [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/) - [Sort Integers by The Number of 1 Bits](https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/) - [XOR Operation in an Array](https://leetcode.com/problems/xor-operation-in-an-array/) - [Count the Number of Consistent Strings](https://leetcode.com/problems/count-the-number-of-consistent-strings/) - [Decode XORed Array](https://leetcode.com/problems/decode-xored-array/) - [Sum of All Subset XOR Totals](https://leetcode.com/problems/sum-of-all-subset-xor-totals/) - [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring/) ## Medium - [Subsets](https://leetcode.com/problems/subsets/) - [Subsets II](https://leetcode.com/problems/subsets-ii/) - [Single Number II](https://leetcode.com/problems/single-number-ii/) - [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) - [Gray Code](https://leetcode.com/problems/gray-code/) - [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) ## Hard - [Minimum Number of Flips to onvert Binary Matrix to zero matrix](https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/) - [Minimum cost to connect two group of points](https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/) - [Find XOR Sum of All Pairs Bitwise AND](https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/) # Additionally - Click on [*Show problem tags*](https://leetcode.com/tag/bit-manipulation/) and do the questions that contains tags of topics we have covered so far. ================================================ FILE: assignments/12-math.md ================================================ # [Video link](https://youtu.be/lmSpZ0bjCyQ) ## Problems - Click on [*Show problem tags*](https://leetcode.com/tag/math/) and do the questions that contains tags of topics we have covered so far. ## Easy - [Roman to Integer.](https://leetcode.com/problems/roman-to-integer/) - [Happy Number.](https://leetcode.com/problems/happy-number/) - [Armstrong Numbers ](https://practice.geeksforgeeks.org/problems/armstrong-numbers2727/1/?category[]=Mathematical&category[]=Mathematical&page=2&query=category[]Mathematicalpage2category[]Mathematical) - [Power of Four](https://leetcode.com/problems/power-of-four/) - [Factorial](https://practice.geeksforgeeks.org/problems/factorial5739/1/?category[]=Mathematical&category[]=Mathematical&page=3&query=category[]Mathematicalpage3category[]Mathematical) - [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) - [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) - [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) - [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) - [Add Binary](https://leetcode.com/problems/add-binary/) - [Power of Two](https://leetcode.com/problems/power-of-two/) ## Medium - [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) - [Unique Paths](https://leetcode.com/problems/unique-paths/) - [Gray Code](https://leetcode.com/problems/gray-code/) - [Perfect Squares](https://leetcode.com/problems/perfect-squares/) - [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) - [Angle Between Hands of a Clock](https://leetcode.com/problems/angle-between-hands-of-a-clock/) - [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) - [The kth Factor of n](https://leetcode.com/problems/the-kth-factor-of-n/) - [Queries on Number of Points Inside a Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/) - [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) - [Multiply Strings](https://leetcode.com/problems/multiply-strings/) - [Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/) - [Integer Break](https://leetcode.com/problems/integer-break/) ## Hard - [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) - [Basic Calculator](https://leetcode.com/problems/basic-calculator/) - [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) - [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) ================================================ FILE: assignments/13-complexities.md ================================================

Recurrence Questions:

Akra Bazzi:

================================================ FILE: assignments/14-oop.md ================================================ # Important Topics - [Kunal's notes](https://github.com/kunal-kushwaha/DSA-Bootcamp-Java/tree/main/lectures/17-oop/notes) - [Object Oriented Paradigms](https://www.geeksforgeeks.org/object-oriented-programming-oops-concept-in-java/) `GFG` - [Constructors in Java](https://www.geeksforgeeks.org/constructors-in-java/) `GFG` - [Constructor chaining in Java](https://www.geeksforgeeks.org/constructor-chaining-java-examples/) `GFG` - [Inheritance in Java](https://www.geeksforgeeks.org/inheritance-in-java/) `GFG` - [Overriding in Java](https://www.geeksforgeeks.org/overriding-in-java/) `GFG` - [Abstraction in Java](https://www.geeksforgeeks.org/abstraction-in-java-2/) `GFG` - [Access modifiers in Java](https://www.geeksforgeeks.org/access-modifiers-java/) `GFG` - [Wrapper Classes in Java](https://www.geeksforgeeks.org/wrapper-classes-java/) `GFG` - [Need of wrapper classes in Java](https://www.geeksforgeeks.org/need-of-wrapper-classes-in-java/) `GFG` - [this keyowrd in Java](https://www.javatpoint.com/this-keyword) `Javatpoint` - [Important keyowrds in Java inheritance - extends,implements,super,instanceof](https://www.tutorialspoint.com/java/java_inheritance.htm) `Tutorialspoint` - [Instance initializer block](https://www.javatpoint.com/instance-initializer-block) `Javatpoint` - [Dynamic Method Dispatch or Runtime Polymorphism in Java](https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/) `GFG` - [Cohesion in Java](https://www.geeksforgeeks.org/cohesion-in-java/) `GFG` - [Coupling in Java](https://www.geeksforgeeks.org/coupling-in-java/) `GFG` # Interview Questions - [Can we declare main() method as private or protected or with no access modifier in java?](https://www.tutorialspoint.com/can-we-declare-main-method-as-private-or-protected-or-with-no-access-modifier-in-java) `Tutorialspoint` - [Difference between Method Overloading and Method Overriding in Java?](https://www.geeksforgeeks.org/difference-between-method-overloading-and-method-overriding-in-java/) `GFG` - [Can we declare interface members as private or protected in java8?](https://www.tutorialspoint.com/can-we-declare-interface-members-as-private-or-protected-in-java8) `Tutorialspoint` - [Can we override a private or static method in Java?](https://www.tutorialspoint.com/can-we-override-a-private-or-static-method-in-java) `Tutorialspoint` - [What is diamond problem in Java?](https://www.javatpoint.com/what-is-diamond-problem-in-java) `Javatpoint` - [Can we pass this keyword as argument in a method call?](https://www.javatpoint.com/this-keyword#:~:text=this%3A%20to%20pass%20as%20an%20argument%20in%20the%20method) `Javatpoint` - [Java constructor returns a value, but what?](https://www.javatpoint.com/java-constructor-returns-a-value-but-what) `Javatpoint` - [What is covariant return type?](https://www.javatpoint.com/covariant-return-type) `Javatpoint` - [Private classes and singleton classes in Java](https://www.geeksforgeeks.org/private-constructors-and-singleton-classes-in-java/) `GFG` - [How to prevent Singleton Pattern from Reflection, Serialization and Cloning?](https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-serialization-cloning/) `GFG` - [Double-Check Locking For Singleton Class](https://www.geeksforgeeks.org/java-program-to-demonstrate-the-double-check-locking-for-singleton-class/) `GFG` # Practice Problems - [Inheritance I](https://www.hackerrank.com/challenges/java-inheritance-1/problem?isFullScreen=true) `HackerRank` - [Inheritance II](https://www.hackerrank.com/challenges/java-inheritance-2/problem?isFullScreen=true) `HackerRank` - [Java Abstract class](https://www.hackerrank.com/challenges/java-abstract-class/problem?isFullScreen=true) `HackerRank` - [Interface](https://www.hackerrank.com/challenges/java-interface/problem?isFullScreen=true) `HackerRank` - [Method Overriding I](https://www.hackerrank.com/challenges/java-method-overriding/problem?isFullScreen=true) `HackerRank` - [Method Overriding II (Use super keyword)](https://www.hackerrank.com/challenges/java-method-overriding-2-super-keyword/problem?isFullScreen=true) `HackerRank` - [Java instanceof keyword](https://www.hackerrank.com/challenges/java-instanceof-keyword/problem?isFullScreen=true) `HackerRank` - [Java Iterator](https://www.hackerrank.com/challenges/java-iterator/problem?isFullScreen=true) `HackerRank` ================================================ FILE: assignments/15-linkedlist.md ================================================ # Problems ## Easy - [Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) `leetcode` - [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) `leetcode` - [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) `leetcode` - [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) `leetcode` - [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) `leetcode` - [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) `leetcode` `Snapdeal` - [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) `leetcode` - [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) `leetcode` `Samsung` - [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)`leetcode` - [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) `leetcode` - [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) `leetcode` ## Medium - [Design Twitter](https://leetcode.com/problems/design-twitter/) `leetcode` - [ Design Linked List](https://leetcode.com/problems/design-linked-list/) `leetcode` - [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) `leetcode` - [Reorder List](https://leetcode.com/problems/reorder-list/) `leetcode` - [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) `leetcode` `HSBC` - [Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) `leetcode` - [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) `leetcode` `TCS` `Amazon` `Microsoft` `Facebook` `Qualcomm` - [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/) `leetcode` - [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) `leetcode` - [Flatten a Multilevel Doubly Linked List](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/) `leetcode` `Amazon` - [Rotate List](https://leetcode.com/problems/rotate-list/) `leetcode` `Microsoft` - [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) `leetcode` - [LRU Cache](https://leetcode.com/problems/lru-cache/) `leetcode` - [Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) `leetcode` `Amex` - [Design Browser History](https://leetcode.com/problems/design-browser-history/) `leetcode` - [Partition list](https://leetcode.com/problems/partition-list/) `leetcode` - [Find first node of loop in a linked list](https://www.geeksforgeeks.org/find-first-node-of-loop-in-a-linked-list/) `GFG` - [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)`leetcode` - [Remove Zero Sum Consecutive Nodes from Linked List](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/) `leetcode` - [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)`leetcode` - [ Reverse Nodes in Even Length Groups](https://leetcode.com/problems/reverse-nodes-in-even-length-groups/)`leetcode` - [ Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)`leetcode` - [Sort List](https://leetcode.com/problems/sort-list/)`leetcode` - [ Merge In Between Linked Lists](https://leetcode.com/problems/merge-in-between-linked-lists/)`leetcode` - [Design Browser History](https://leetcode.com/problems/design-browser-history/)`leetcode` - [Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/)`leetcode` - [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/)`leetcode` - [ Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)`leetcode` - [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)`leetcode` - [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/)`leetcode` - [ Find the Minimum and Maximum Number of Nodes Between Critical Points](https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/)`leetcode` ## Hard - [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) `leetcode` - [LFU Cache](https://leetcode.com/problems/lfu-cache/) `leetcode` `Google` - [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) `leetcode` - [Clone a linked list with next and random pointer](https://www.geeksforgeeks.org/clone-linked-list-next-random-pointer-o1-space/) `GFG` `Google` `Flipkart` - [All O'one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) `leetcode` - [Design Skiplist](https://leetcode.com/problems/design-skiplist/) `leetcode` ================================================ FILE: assignments/16-stack-queue.md ================================================ # Problems ## Easy - [Next greater element I](https://leetcode.com/problems/next-greater-element-i/) `leetcode` - [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) `leetcode` - [Min Stack](https://leetcode.com/problems/min-stack/) `leetcode` - [Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/) `leetcode` - [Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) `leetcode` - [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) `leetcode` - [Reverse First K elements of Queue](https://practice.geeksforgeeks.org/problems/reverse-first-k-elements-of-queue/1/) `GFG` - [Delete middle element of a stack](https://practice.geeksforgeeks.org/problems/delete-middle-element-of-a-stack/1/) `GFG` - [Inorder Traversal (Iterative)](https://practice.geeksforgeeks.org/problems/inorder-traversal-iterative/1/) `GFG` - [Preorder traversal (Iterative)](https://practice.geeksforgeeks.org/problems/preorder-traversal-iterative/1/) `GFG` - [Flood fill](https://leetcode.com/problems/flood-fill/) `leetcode` - [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) `leetcode` ## Medium - [Design a Stack With Increment Operation](https://leetcode.com/problems/design-a-stack-with-increment-operation/) `leetcode` - [Minimum Add to Make Parentheses Valid](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/) `leetcode` - [Decode String](https://leetcode.com/problems/decode-string/) `leetcode` - [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) `leetcode` - [132 Pattern](https://leetcode.com/problems/132-pattern/) `leetcode` - [Design circular Queue](https://leetcode.com/problems/design-circular-queue/) `leetcode` - [Find the Most Competitive Subsequence](https://leetcode.com/problems/find-the-most-competitive-subsequence/) `leetcode` - [Design Front Middle Back Queue](https://leetcode.com/problems/design-front-middle-back-queue/) `leetcode` - [Circular tour](https://practice.geeksforgeeks.org/problems/circular-tour/1) `GFG` `Amex` `Amazon` - [Task Scheduler](https://leetcode.com/problems/task-scheduler/) `leetcode` - [Stock span problem](https://practice.geeksforgeeks.org/problems/stock-span-problem-1587115621/1/) `GFG` - [Max Rectangle](https://practice.geeksforgeeks.org/problems/max-rectangle/1/) `GFG` - [The Celebrity Problem](https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1/) `Google` `GFG` - [Maximum Rectangular Area in a Histogram](https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1/) `GFG` - [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) `leetcode` - [Snake and Ladders](https://leetcode.com/problems/snakes-and-ladders/) `leetcode` ## Hard - [Longest Valid Parantheses](https://leetcode.com/problems/longest-valid-parentheses/) `leetcode` - [Sliding window maximum](https://leetcode.com/problems/sliding-window-maximum/) `leetcode` - [Brace Expansion II](https://leetcode.com/problems/brace-expansion-ii/) `leetcode` - [Card Rotation](https://practice.geeksforgeeks.org/problems/card-rotation5834/1/) `GFG` - [Minimum steps to reach target by a Knight](https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/) `GFG` - [Count number of islands](https://leetcode.com/problems/number-of-islands/) `leetcode` ================================================ FILE: assignments/17-trees.md ================================================ # Problems ## Easy - [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) `leetcode` - [Same Tree](https://leetcode.com/problems/same-tree/) `leetcode` - [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) `leetcode` - [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) `leetcode` - [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) `leetcode` - [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) `leetcode` - [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) `leetcode` - [Path Sum](https://leetcode.com/problems/path-sum/) `leetcode` - [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) `leetcode` - [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) `leetcode` - [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) `leetcode` - [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) `leetcode` - [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) `leetcode` - [Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/) `leetcode` - [Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) `leetcode` - [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) `leetcode` ## Medium - [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) `leetcode` - [All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/) `leetcode` - [Validate Binary Tree Nodes](https://leetcode.com/problems/validate-binary-tree-nodes/) `leetcode` - [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) `leetcode` - [Closest Nodes Queries in a Binary Search Tree](https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/) `leetcode` - [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) `leetcode` - [Linked List in Binary Tree](https://leetcode.com/problems/linked-list-in-binary-tree/) `leetcode` - [Operations on Tree](https://leetcode.com/problems/operations-on-tree/) `leetcode` - [Verify Preorder Serialization of a Binary Tree](https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/) `leetcode` - [Kth Largest Sum in a Binary Tree](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/) `leetcode` - [Count Nodes With the Highest Score](https://leetcode.com/problems/count-nodes-with-the-highest-score/) `leetcode` - [Path Sum III](https://leetcode.com/problems/path-sum-iii/) `leetcode` - [Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/) `leetcode` - [Most Profitable Path in a Tree](https://leetcode.com/problems/most-profitable-path-in-a-tree/) `leetcode` - [Step-By-Step Directions From a Binary Tree Node to Another](https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/) `leetcode` - [Logical OR of Two Binary Grids Represented as Quad-Trees](https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/) `leetcode` - [Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/) `leetcode` ## Hard - [Kth Ancestor of a Tree Node](https://leetcode.com/problems/kth-ancestor-of-a-tree-node/) `leetcode` - [Difference Between Maximum and Minimum Price Sum](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/) `leetcode` - [Merge BSTs to Create Single BST](https://leetcode.com/problems/merge-bsts-to-create-single-bst/) `leetcode` - [Frog Position After T Seconds](https://leetcode.com/problems/frog-position-after-t-seconds/) `leetcode` - [Height of Binary Tree After Subtree Removal Queries](https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/) `leetcode` - [Collect Coins in a Tree](https://leetcode.com/problems/collect-coins-in-a-tree/) `leetcode` - [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) `leetcode` - [Tree of Coprimes](https://leetcode.com/problems/tree-of-coprimes/) `leetcode` - [Maximum Sum BST in Binary Tree](https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/) `leetcode` - [Minimize the Total Price of the Trips](https://leetcode.com/problems/minimize-the-total-price-of-the-trips/) `leetcode` - [Number Of Ways To Reconstruct A Tree](https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/) `leetcode` - [Smallest Missing Genetic Value in Each Subtree](https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/) `leetcode` - [Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/) `leetcode` - [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) `leetcode` - [Number of Ways to Reorder Array to Get Same BST](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/) `leetcode` - [Count Number of Possible Root Nodes](https://leetcode.com/problems/count-number-of-possible-root-nodes/) `leetcode` - [Count Ways to Build Rooms in an Ant Colony](https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/) `leetcode` - [Minimum Score After Removals on a Tree](https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/) `leetcode` - [Create Components With Same Value](https://leetcode.com/problems/create-components-with-same-value/) `leetcode` - [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) `leetcode` - [Longest Path With Different Adjacent Characters](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/) `leetcode` ================================================ FILE: assignments/18-heaps.md ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/encodings.xml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/misc.xml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/modules.xml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/project-template.xml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/.idea/vcs.xml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/first-idea-program.iml ================================================ ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Basics.java ================================================ package com.kunal; public class Basics { public static void main(String[] args) { // int a = 10; // if (a == 10) { // System.out.println("Hello World"); // } // int count = 1; // while(count != 5) { // System.out.println(count); // count++; // } // for loop for(int count = 1; count != 5; count++) { System.out.println(count); } } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Inputs.java ================================================ package com.kunal; import java.util.Scanner; public class Inputs { public static void main(String[] args) { Scanner input = new Scanner(System.in); // System.out.print("Please enter some input: "); // int rollno = input.nextInt(); // System.out.println("Your roll number is " + rollno); // String name = input.next(); // System.out.println(name); // float marks = input.nextFloat(); // System.out.println(marks); } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Main.java ================================================ package com.kunal; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(input.nextLine()); } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Prime.java ================================================ package com.kunal; import java.util.Scanner; public class Prime { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); int n = in.nextInt(); if(n <= 1) { System.out.println("Neither prime nor composite"); return; } int c = 2; while (c * c <= n) { if (n % c == 0) { System.out.println("Not Prime"); return; } c = c + 1; // c++; } if (c * c > n) { System.out.println("Prime"); } } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Primitives.java ================================================ package com.kunal; public class Primitives { public static void main(String[] args) { int rollno = 64; char letter = 'r'; float marks = 98.67f; double largeDecimalNumbers = 4567654.4567; long largeInteger = 34567834567876543L; boolean check = false; float c = 30.6f; c++; // c = (int)(c) + 1; System.out.println(c); } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Sum.java ================================================ package com.kunal; import java.util.Scanner; public class Sum { public static void main(String[] args) { Scanner input = new Scanner(System.in); float num1 = input.nextFloat(); float num2 = input.nextFloat(); float sum = num1 + num2; System.out.println("Sum = " + sum); } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/Temperature.java ================================================ package com.kunal; import java.util.Scanner; public class Temperature { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter temp in C: "); float tempC = in.nextFloat(); float tempF = (tempC * 9/5) + 32; System.out.println(tempF); } } ================================================ FILE: lectures/05-first-java-program/first-idea-program/src/com/kunal/TypeCasting.java ================================================ package com.kunal; import java.util.Scanner; public class TypeCasting { public static void main(String[] args) { Scanner input = new Scanner(System.in); // float num = input.nextFloat(); // int num = input.nextInt(); // System.out.println(num); // type casting int num = (int)(67.56f); // System.out.println(num); // automatic type promotion in expressions // int a = 257; // byte b = (byte)(a); // 257 % 256 = 1 // byte a = 40; // byte b = 50; // byte c = 100; // int d = a * b / c; // // System.out.println(d); // byte b = 50; // b = b * 2; // int number = 'A'; // System.out.println("你好"); // System.out.println(3 * 6); byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = 0.1234; double result = (f * b) + (i / c) - (d * s); // float + int - double = double System.out.println((f * b) + " " + (i / c) + " " + (d * s)); System.out.println(result); } } ================================================ FILE: lectures/05-first-java-program/first-tutorial/Demo.java ================================================ public class Demo { public static void main(String[] args) { System.out.println(args[1]); } } ================================================ FILE: lectures/05-first-java-program/first-tutorial/Main.java ================================================ public class Demo { public static void main(String[] args) { System.out.println(args[0]); } } ================================================ FILE: lectures/05-first-java-program/notes/literals.txt ================================================ Literals: Java Literals are syntactic representations of boolean, character, numeric, or string data. Example: 4 is an integer literal. Identifiers: Identifiers are the names of variables, methods, classes, packages and interfaces Octal values are denoted in Java by a leading zero. Normal decimal numbers cannot have a leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7 range. You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15. When a literal value is assigned to a byte or short variable, no error is generated if the literal value is within the range of the target type. An integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is of type long. You do this by appending an upper- or lowercase L to the literal. Beginning with JDK 7, you can also specify integer literals using binary. To do so, prefix the value with 0b or 0B. For example, this specifies the decimal value 10 using a binary literal: int x = 0b1010; int x = 123_456_789; the value given to x will be 123,456,789. The underscores will be ignored. Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. Hexadecimal floating-point literals are also supported, but they are rarely used. They must be in a form similar to scientific notation, but a P or p, rather than an E or e, is used. For example, 0x12.2P2 is a valid floating-point literal. The value following the P, called the binary exponent, indicates the power-of-two by which the number is multiplied. Therefore, 0x12.2P2 represents 72.5. double num = 9_423_497_862.0; the value given to num will be 9,423,497,862.0 double num = 9_423_497.1_0_9; In this case, the fractional part is .109 Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1, nor does the false literal equal 0. As you may know, in some other languages, including C/C++, strings are implemented as arrays of characters. However, this is not the case in Java. Strings are actually object types. Because Java implements strings as objects, Java includes extensive string-handling capabilities that are both powerful and easy to use. The remainder a % b is defined such that (a / b) * b + a % b is always equal to a : System.out.println(-15 % 2); // -1 System.out.println(15 % -2); // 1 ================================================ FILE: lectures/05-first-java-program/notes/notes.txt ================================================ Terminal: echo $PATH # This is where it looks for the applications that we want to open. Class name always starts with a capital letter. To understand code and see control flow, debug the code after putting breakpoint. We can also change the values in debugger window to see what will happen at a particular value. Input: class Scanner to scan something i.e. Input something command & click on class name to open class file. ex: cmd & click on 'Scanner' javac -d . cmd.java The -d switch specifies the destination where to put the generated class file. OBJECT CLASS : Object class is present in java.lang package.Every class in Java is directly or indirectly derived from the Object class. If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program. There are methods in Object class: toString(), hashCode(), equals(Object obj), getClass(), finalize(), clone(), etc. NUMBER CLASS : Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package.There are mainly six subclasses under Number class.These sub-classes define some useful methods which are used frequently while dealing with numbers. Byte, Integer, Double, Short, Float, Long NOTE : Primitive Wrapper Classes are Immutable in Java. ================================================ FILE: lectures/05-first-java-program/notes/type_conversion&casting.txt ================================================ Type Conversion and Casting: Java’s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: • The two types are compatible. • The destination type is larger than the source type. Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char. Casting Incompatible Types Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type. For example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range. int a; byte b; b = (byte) a; A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. Automatic Type Promotion in Expressions: int a = 257; byte b = (byte)a; When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case. byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when evaluating an expression. This means that the subexpression a*b is performed using integers—not bytes. byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte! The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. The Type Promotion Rules: Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands are double, the result is double. class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); } } Let’s look closely at the type promotions that occur in this line from the program: double result = (f * b) + (i / c) - (d * s); In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in d * s, the value of s is promoted to double, and the type of the subexpression is double. Finally, these three intermediate values, float, int, and double, are considered. The outcome of float plus an int is a float. Then the resultant float minus the last double is promoted to double, which is the type for the final result of the expression. ================================================ FILE: lectures/06-conditions-loops/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/06-conditions-loops/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/06-conditions-loops/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/code.iml ================================================ ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Calculator.java ================================================ package com.kunal; import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Take input from user till user does not press X or x int ans = 0; while (true) { // take the operator as input System.out.print("Enter the operator: "); char op = in.next().trim().charAt(0); if (op == '+' || op == '-' || op == '*' || op == '/' || op == '%') { // input two numbers System.out.print("Enter two numbers: "); int num1 = in.nextInt(); int num2 = in.nextInt(); if (op == '+') { ans = num1 + num2; } if (op == '-') { ans = num1 - num2; } if (op == '*') { ans = num1 * num2; } if (op == '/') { if (num2 != 0) { ans = num1 / num2; } } if (op == '%') { ans = num1 % num2; } } else if (op == 'x' || op == 'X') { break; } else { System.out.println("Invalid operation!!"); } System.out.println(ans); } } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/CaseCheck.java ================================================ package com.kunal; import java.util.Scanner; public class CaseCheck { public static void main(String[] args) { Scanner in = new Scanner(System.in); char ch = in.next().trim().charAt(0); if (ch >= 'a' && ch <= 'z') { System.out.println("Lowercase"); } else { System.out.println("Uppercase"); } } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Conditionals.java ================================================ package com.kunal; public class Conditionals { public static void main(String[] args) { /* Syntax of if statements: if (boolean expression T or F) { // body } else { // do this } */ int salary = 25400; // if (salary > 10000) { // salary = salary + 2000; // } else { // salary = salary + 1000; // } // multiple if-else // if (salary > 10000) { // salary += 2000; // salary = salary + 2000 // } else if (salary > 20000) { // salary += 3000; // } else { // salary += 1000; // } // // System.out.println(salary); int a = 10; int b = 40; if (a != 35) { System.out.println("Hello World"); } } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/CountNums.java ================================================ package com.kunal; public class CountNums { public static void main(String[] args) { int n = 45535; int count = 0; while (n > 0) { int rem = n % 10; if (rem == 5) { count++; } n = n / 10; // n /= 10 } System.out.println(count); } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Fibo.java ================================================ package com.kunal; import java.util.Scanner; public class Fibo { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a = 0; int b = 1; int count = 2; while (count <= n) { int temp = b; b = b + a; a = temp; count++; } System.out.println(b); } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Largest.java ================================================ package com.kunal; import java.util.Scanner; public class Largest { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); // Q: Find the largest of the 3 numbers // int max = a; // if (b > max) { // max = b; // } // if (c > max) { // max = c; // } // int max = 0; // if (a > b) { // max = a; // } else { // max = b; // } // // if (c > max) { // max = c; // } int max = Math.max(c, Math.max(a, b)); System.out.println(max); } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Loops.java ================================================ package com.kunal; import java.util.Scanner; public class Loops { public static void main(String[] args) { /* Syntax of for loops: for (initialisation; condition; increment/decrement) { // body } */ // Q: Print numbers from 1 to 5 // for (int num = 1; num <= 5; num += 2) { // System.out.println(num); // } // print numbers from 1 to n Scanner in = new Scanner(System.in); // int n = in.nextInt(); // for (int num = 1; num <= n; num++) { //// System.out.print(num + " "); // System.out.println("Hello World"); // } // while loops /* Syntax: while (condition) { // body } */ // for (int num = 1; num <= 5; num += 2) { // System.out.println(num); // } int num = 1; while (num <= 5) { // System.out.println(num); num += 1; } // do while /* do { // body } while (condition); */ int n = 1; do { System.out.println("Hello World"); } while (n != 1); } } ================================================ FILE: lectures/06-conditions-loops/code/src/com/kunal/Reverse.java ================================================ package com.kunal; public class Reverse { public static void main(String[] args) { int num = 123456; int ans = 0; while (num > 0) { int rem = num % 10; num /= 10; ans = ans * 10 + rem; } System.out.println(ans); } } ================================================ FILE: lectures/06-conditions-loops/switch/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/06-conditions-loops/switch/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/06-conditions-loops/switch/.idea/encodings.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/switch/.idea/misc.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/switch/.idea/modules.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/switch/.idea/project-template.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/switch/.idea/vcs.xml ================================================ ================================================ FILE: lectures/06-conditions-loops/switch/src/com/kunal/Main.java ================================================ package com.kunal; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // String fruit = in.next(); // // switch (fruit) { // case "Mango" -> System.out.println("King of fruits"); // case "Apple" -> System.out.println("A sweet red fruit"); // case "Orange" -> System.out.println("Round fruit"); // case "Grapes" -> System.out.println("Small fruit"); // default -> System.out.println("please enter a valid fruit"); // } int day = in.nextInt(); // switch (day) { // case 1 -> System.out.println("Monday"); // case 2 -> System.out.println("Tuesday"); // case 3 -> System.out.println("Wednesday"); // case 4 -> System.out.println("Thursday"); // case 5 -> System.out.println("Friday"); // case 6 -> System.out.println("Saturday"); // case 7 -> System.out.println("Sunday"); // } // switch (day) { // case 1: // case 2: // case 3: // case 4: // case 5: // System.out.println("Weekday"); // break; // case 6: // case 7: // System.out.println("Weekend"); // break; // } switch (day) { case 1, 2, 3, 4, 5 -> System.out.println("Weekday"); case 6, 7 -> System.out.println("Weekend"); } } } ================================================ FILE: lectures/06-conditions-loops/switch/src/com/kunal/NestedSwitch.java ================================================ package com.kunal; import java.util.Scanner; public class NestedSwitch { public static void main(String[] args) { Scanner in = new Scanner(System.in); int empID = in.nextInt(); String department = in.next(); switch (empID) { case 1: System.out.println("Kunal Kushwaha"); break; case 2: System.out.println("Rahul Rana"); break; case 3: System.out.println("Emp Number 3"); switch (department) { case "IT": System.out.println("IT Department"); break; case "Management": System.out.println("Management Department"); break; default: System.out.println("No department entered"); } break; default: System.out.println("Enter correct EmpID"); } // better way to write switch (empID) { case 1 -> System.out.println("Kunal Kushwaha"); case 2 -> System.out.println("Rahul Rana"); case 3 -> { System.out.println("Emp Number 3"); switch (department) { case "IT" -> System.out.println("IT Department"); case "Management" -> System.out.println("Management Department"); default -> System.out.println("No department entered"); } } default -> System.out.println("Enter correct EmpID"); } } } ================================================ FILE: lectures/06-conditions-loops/switch/switch.iml ================================================ ================================================ FILE: lectures/07-methods/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/07-methods/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/07-methods/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/07-methods/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/07-methods/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/07-methods/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/07-methods/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/07-methods/code/code.iml ================================================ ================================================ FILE: lectures/07-methods/code/src/com/kunal/ChangeValue.java ================================================ package com.kunal; import java.util.Arrays; public class ChangeValue{ public static void main(String[] args) { // create an array int[] arr = {1, 3, 2, 45, 6}; change(arr); System.out.println(Arrays.toString(arr)); } static void change(int[] nums) { nums[0] = 99; // if you make a change to the object via this ref variable, same object will be changed } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Greeting.java ================================================ package com.kunal; public class Greeting { public static void main(String[] args) { greeting(); } static void greeting() { System.out.println("Hello World"); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Main.java ================================================ package com.kunal; import java.util.Scanner; public class Main { public static void main(String[] args) { // Q: take input of 2 numbers and print the sum Scanner in = new Scanner(System.in); int num1, num2, sum; System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); System.out.print("Enter number 1: "); num1 = in.nextInt(); System.out.print("Enter number 2: "); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum = " + sum); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Overloading.java ================================================ package com.kunal; public class Overloading { public static void main(String[] args) { // fun(67); // fun("Kunal Kushwaha"); int ans = sum(3, 4, 78); System.out.println(ans); } static int sum(int a, int b) { return a + b; } static int sum(int a, int b, int c) { return a + b + c; } static void fun(int a) { System.out.println("first one"); System.out.println(a); } static void fun(String name) { System.out.println("Second one"); System.out.println(name); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/PassingExample.java ================================================ package com.kunal; public class PassingExample { public static void main(String[] args) { String chacha = "Iron Man"; greet(chacha); } static void greet(String naam) { System.out.println(naam); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Questions.java ================================================ package com.kunal; import java.util.Scanner; public class Questions { public static void main(String[] args) { Scanner in = new Scanner(System.in); // int n = in.nextInt(); // boolean ans = isPrime(n); // System.out.println(ans); for (int i = 100; i < 1000; i++) { if (isArmstrong(i)) { System.out.print(i + " "); } } } // print all the 3 digits armstrong numbers static boolean isArmstrong(int n) { int original = n; int sum = 0; while (n > 0) { int rem = n % 10; n = n / 10; sum = sum + rem*rem*rem; } return sum == original; } static boolean isPrime(int n) { if (n <= 1) { return false; } int c = 2; while (c * c <= n) { if (n % c == 0) { return false; } c++; } return c * c > n; } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Scope.java ================================================ package com.kunal; public class Scope { public static void main(String[] args) { int a = 10; int b = 20; String name = "Kunal"; { // int a = 78; // already initialised outside the block in the same method, hence you cannot initialise again a = 100; // reassign the origin ref variable to some other value System.out.println(a); int c = 99; name = "Rahul"; System.out.println(name); // values initialised in this block, will remain in block } int c = 900; System.out.println(a); System.out.println(name); // System.out.println(c); // cannot use outside the block // scoping in for loops for (int i = 0; i < 4; i++) { // System.out.println(i); int num = 90; a = 10000; } System.out.println(); } static void random(int marks) { int num = 67; System.out.println(num); System.out.println(marks); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Shadowing.java ================================================ package com.kunal; public class Shadowing { static int x = 90; // this will be shadowed at line 8 public static void main(String[] args) { System.out.println(x); // 90 int x; // the class variable at line 4 is shadowed by this // System.out.println(x); // scope will begin when value is initialised x = 40; System.out.println(x); // 40 fun(); } static void fun() { System.out.println(x); } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/StringExample.java ================================================ package com.kunal; import java.util.Scanner; public class StringExample { public static void main(String[] args) { // String message = greet(); // System.out.println(message); Scanner in = new Scanner(System.in); System.out.print("Enter your name: "); String naam = in.next(); String personalised = myGreet(naam); System.out.println(personalised); } static String myGreet(String name) { String message = "Hello " + name; return message; } static String greet() { String greeting = "how are you"; return greeting; } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Sum.java ================================================ package com.kunal; import java.util.Scanner; public class Sum { public static void main(String[] args) { // int ans = sum2(); // System.out.println(ans); int ans = sum3(20, 30); System.out.println(ans); } // pass the value of numbers when you are calling the method in main() static int sum3(int a, int b) { int sum = a + b; return sum; } // return the value static int sum2() { Scanner in = new Scanner(System.in); System.out.print("Enter number 1: "); int num1 = in.nextInt(); System.out.print("Enter number 2: "); int num2 = in.nextInt(); int sum = num1 + num2; return sum; // System.out.println("This will never execute"); } static void sum() { Scanner in = new Scanner(System.in); System.out.print("Enter number 1: "); int num1 = in.nextInt(); System.out.print("Enter number 2: "); int num2 = in.nextInt(); int sum = num1 + num2; System.out.println("The sum = " + sum); } /* return_type name (arguments) { // body return statement; } */ } ================================================ FILE: lectures/07-methods/code/src/com/kunal/Swap.java ================================================ package com.kunal; public class Swap { public static void main(String[] args) { int a = 10; int b = 20; // swap numbers code // int temp = a; // a = b; // b = temp; swap(a, b); System.out.println(a + " " + b); String name = "Kunal Kushwaha"; changeName(name); System.out.println(name); } static void changeName(String naam) { naam = "Rahul Rana"; // creating a new object } static void swap(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; // this change will only be valid in this function scope only. } } ================================================ FILE: lectures/07-methods/code/src/com/kunal/VarArgs.java ================================================ package com.kunal; import java.util.Arrays; public class VarArgs { public static void main(String[] args) { // fun(); // multiple(2, 3, "Kunal", "Rahul", "dvytsbhusc"); // demo(); } static void demo(int ...v) { System.out.println(Arrays.toString(v)); } static void demo(String ...v) { System.out.println(Arrays.toString(v)); } static void multiple(int a, int b, String ...v) { } static void fun(int ...v) { System.out.println(Arrays.toString(v)); } } ================================================ FILE: lectures/08-arrays/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/08-arrays/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/08-arrays/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/08-arrays/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/08-arrays/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/08-arrays/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/08-arrays/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/08-arrays/code/code.iml ================================================ ================================================ FILE: lectures/08-arrays/code/src/com/kunal/ArrayListExample.java ================================================ package com.kunal; import java.util.ArrayList; import java.util.Scanner; public class ArrayListExample { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Syntax ArrayList list = new ArrayList<>(5); // list.add(67); // list.add(234); // list.add(654); // list.add(43); // list.add(654); // list.add(8765); // System.out.println(list.contains(765432)); // System.out.println(list); // list.set(0, 99); // // list.remove(2); // // System.out.println(list); // input for (int i = 0; i < 5; i++) { list.add(in.nextInt()); } // get item at any index for (int i = 0; i < 5; i++) { System.out.println(list.get(i)); // pass index here, list[index] syntax will not work here } System.out.println(list); } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/ColNoFixed.java ================================================ package com.kunal; public class ColNoFixed { public static void main(String[] args) { int[][] arr = { {1, 2, 3, 4}, {5, 6}, {7, 8, 9} }; for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { System.out.print(arr[row][col] + " "); } System.out.println(); } } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/Input.java ================================================ package com.kunal; import java.util.Arrays; import java.util.Scanner; public class Input { public static void main(String[] args) { Scanner in = new Scanner(System.in); // array of primitives int[] arr = new int[5]; arr[0] = 23; arr[1] = 45; arr[2] = 233; arr[3] = 543; arr[4] = 3; // [23, 45, 233, 543, 3] System.out.println(arr[3]); // input using for loops for (int i = 0; i < arr.length; i++) { arr[i] = in.nextInt(); } // // System.out.println(Arrays.toString(arr)); // for (int i = 0; i < arr.length; i++) { // System.out.print(arr[i] + " "); // } // for(int num : arr) { // for every element in array, print the element // System.out.print(num + " "); // here num represents element of the array // } // System.out.println(arr[5]); // index out of bound error // array of objects String[] str = new String[4]; for (int i = 0; i < str.length; i++) { str[i] = in.next(); } System.out.println(Arrays.toString(str)); // modify str[1] = "kunal"; System.out.println(Arrays.toString(str)); } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/Main.java ================================================ package com.kunal; public class Main { public static void main(String[] args) { // Q: store a roll number int a = 19; // Q: store a person's name String name = "Kunal Kushwaha"; // Q: store 5 roll numbers int rno1 = 23; int rno2 = 55; int rno3 = 18; // syntax // datatype[] variable_name = new datatype[size]; // store 5 roll numbers: // int[] rnos = new int[5]; // // or directly // int[] rnos2 = {23, 12, 45, 32, 15}; int[] ros; // declaration of array. ros is getting defined in the stack ros = new int[5]; // initialisation: actually here object is being created in the memory (heap) // System.out.println(ros[1]); String[] arr = new String[4]; System.out.println(arr[0]); // for (String element : arr) { // System.out.println(element); // } } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/Max.java ================================================ package com.kunal; public class Max { public static void main(String[] args) { int[] arr = {1, 3, 2, 9, 18}; System.out.println(maxRange(arr, 1, 3)); } // work on edge cases here, like array being null static int maxRange(int[] arr, int start, int end) { if (start > end) { return -1; } if (arr == null) { return -1; } int maxVal = arr[start]; for (int i = start; i <= end; i++) { if (arr[i] > maxVal) { maxVal = arr[i]; } } return maxVal; } static int max(int[] arr) { if (arr.length == 0) { return -1; } int maxVal = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > maxVal) { maxVal = arr[i]; } } return maxVal; } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/MultiAL.java ================================================ package com.kunal; import java.util.ArrayList; import java.util.Scanner; public class MultiAL { public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList> list = new ArrayList<>(); // initialisation for (int i = 0; i < 3; i++) { list.add(new ArrayList<>()); } // add elements for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { list.get(i).add(in.nextInt()); } } System.out.println(list); } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/MultiDimension.java ================================================ package com.kunal; import java.util.Arrays; import java.util.Scanner; public class MultiDimension { public static void main(String[] args) { /* 1 2 3 4 5 6 7 8 9 */ Scanner in = new Scanner(System.in); // int[][] arr = new int[3][]; // int[][] arr = { // {1, 2, 3}, // 0th index // {4, 5}, // 1st index // {6, 7, 8, 9} // 2nd index -> arr[2] = {6, 7, 8, 9} // }; int[][] arr = new int[3][3]; System.out.println(arr.length); // no of rows // input for (int row = 0; row < arr.length; row++) { // for each col in every row for (int col = 0; col < arr[row].length; col++) { arr[row][col] = in.nextInt(); } } // output // for (int row = 0; row < arr.length; row++) { // // for each col in every row // for (int col = 0; col < arr[row].length; col++) { // System.out.print(arr[row][col] + " "); // } // System.out.println(); // } // output // for (int row = 0; row < arr.length; row++) { // System.out.println(Arrays.toString(arr[row])); // } for(int[] a : arr) { System.out.println(Arrays.toString(a)); } } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/PassinginFunctions.java ================================================ package com.kunal; import java.util.Arrays; public class PassinginFunctions { public static void main(String[] args) { int[] nums = {3, 4, 5, 12}; System.out.println(Arrays.toString(nums)); change(nums); System.out.println(Arrays.toString(nums)); } static void change(int[] arr) { arr[0] = 99; } } ================================================ FILE: lectures/08-arrays/code/src/com/kunal/Swap.java ================================================ package com.kunal; import java.util.Arrays; public class Swap { public static void main(String[] args) { int[] arr = {1, 3, 23, 9, 18, 56}; // swap(arr, 0, 4); reverse(arr); System.out.println(Arrays.toString(arr)); } static void reverse(int[] arr) { int start = 0; int end = arr.length-1; while (start < end) { // swap swap(arr, start, end); start++; end--; } } static void swap(int[] arr, int index1, int index2) { int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; } } ================================================ FILE: lectures/09-linear search/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/09-linear search/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/09-linear search/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/09-linear search/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/09-linear search/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/09-linear search/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/09-linear search/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/09-linear search/code/code.iml ================================================ ================================================ FILE: lectures/09-linear search/code/src/com/kunal/EvenDigits.java ================================================ package com.kunal; // https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ public class EvenDigits { public static void main(String[] args) { int[] nums = {12,345,2,6,7896}; // System.out.println(findNumbers(nums)); System.out.println(digits2(-345678)); } static int findNumbers(int[] nums) { int count = 0; for(int num : nums) { if (even(num)) { count++; } } return count; } // function to check whether a number contains even digits or not static boolean even(int num) { int numberOfDigits = digits(num); /* if (numberOfDigits % 2 == 0) { return true; } return false; */ return numberOfDigits % 2 == 0; } static int digits2(int num) { if (num < 0) { num = num * -1; } return (int)(Math.log10(num)) + 1; } // count number of digits in a number static int digits(int num) { if (num < 0) { num = num * -1; } if (num == 0) { return 1; } int count = 0; while (num > 0) { count++; num = num / 10; // num /= 10 } return count; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/FindMin.java ================================================ package com.kunal; public class FindMin { public static void main(String[] args) { int[] arr = {18, 12, 7, 3, 14, 28}; System.out.println(min(arr)); } // assume arr.length != 0 // return the minimum value in the array static int min(int[] arr) { int ans = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < ans) { ans = arr[i]; } } return ans; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/Main.java ================================================ package com.kunal; public class Main { public static void main(String[] args) { int[] nums = {23, 45, 1, 2, 8, 19, -3, 16, -11, 28}; int target = 19; boolean ans = linearSearch3(nums, target); System.out.println(ans); } // search the target and return true or false static boolean linearSearch3(int[] arr, int target) { if (arr.length == 0) { return false; } // run a for loop for (int element : arr) { if (element == target) { return true; } } // this line will execute if none of the return statements above have executed // hence the target not found return false; } // search the target and return the element static int linearSearch2(int[] arr, int target) { if (arr.length == 0) { return -1; } // run a for loop for (int element : arr) { if (element == target) { return element; } } // this line will execute if none of the return statements above have executed // hence the target not found return Integer.MAX_VALUE; } // search in the array: return the index if item found // otherwise if item not found return -1 static int linearSearch(int[] arr, int target) { if (arr.length == 0) { return -1; } // run a for loop for (int index = 0; index < arr.length; index++) { // check for element at every index if it is = target int element = arr[index]; if (element == target) { return index; } } // this line will execute if none of the return statements above have executed // hence the target not found return -1; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/MaxWealth.java ================================================ package com.kunal; // https://leetcode.com/problems/richest-customer-wealth/ public class MaxWealth { public static void main(String[] args) { } public int maximumWealth(int[][] accounts) { // person = rol // account = col int ans = Integer.MIN_VALUE; for (int[] ints : accounts) { // when you start a new row, take a new sum for that row int sum = 0; for (int anInt : ints) { sum += anInt; } // now we have sum of accounts of person // check with overall ans if (sum > ans) { ans = sum; } } return ans; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/SearchIn2DArray.java ================================================ package com.kunal; import java.util.Arrays; public class SearchIn2DArray { public static void main(String[] args) { int[][] arr = { {23, 4, 1}, {18, 12, 3, 9}, {78, 99, 34, 56}, {18, 12} }; int target = 56; int[] ans = search(arr,target); // format of return value {row, col} System.out.println(Arrays.toString(ans)); System.out.println(max(arr)); System.out.println(Integer.MIN_VALUE); } static int[] search(int[][] arr, int target) { for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { if (arr[row][col] == target) { return new int[]{row, col}; } } } return new int[]{-1, -1}; } static int max(int[][] arr) { int max = Integer.MIN_VALUE; for (int[] ints : arr) { for (int element : ints) { if (element > max) { max = element; } } } return max; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/SearchInRange.java ================================================ package com.kunal; public class SearchInRange { public static void main(String[] args) { int[] arr = {18, 12, -7, 3, 14, 28}; int target = 3456; System.out.println(linearSearch(arr, target, 1, 4)); } static int linearSearch(int[] arr, int target, int start, int end) { if (arr.length == 0) { return -1; } // run a for loop for (int index = start; index <= end; index++) { // check for element at every index if it is = target int element = arr[index]; if (element == target) { return index; } } // this line will execute if none of the return statements above have executed // hence the target not found return -1; } } ================================================ FILE: lectures/09-linear search/code/src/com/kunal/SearchInStrings.java ================================================ package com.kunal; import java.util.Arrays; public class SearchInStrings { public static void main(String[] args) { String name = "Kunal"; char target = 'u'; // System.out.println(search(name, target)); System.out.println(Arrays.toString(name.toCharArray())); } static boolean search2(String str, char target) { if (str.length() == 0) { return false; } for(char ch : str.toCharArray()) { if (ch == target) { return true; } } return false; } static boolean search(String str, char target) { if (str.length() == 0) { return false; } for (int i = 0; i < str.length(); i++) { if (target == str.charAt(i)) { return true; } } return false; } } ================================================ FILE: lectures/10-binary search/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/10-binary search/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/10-binary search/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/10-binary search/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/10-binary search/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/10-binary search/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/10-binary search/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/10-binary search/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/10-binary search/code/code.iml ================================================ ================================================ FILE: lectures/10-binary search/code/src/com/kunal/BinarySearch.java ================================================ package com.kunal; public class BinarySearch { public static void main(String[] args) { int[] arr = {-18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89}; int target = 22; int ans = binarySearch(arr, target); System.out.println(ans); } // return the index // return -1 if it does not exist static int binarySearch(int[] arr, int target) { int start = 0; int end = arr.length - 1; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; } else if (target > arr[mid]) { start = mid + 1; } else { // ans found return mid; } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/Ceiling.java ================================================ package com.kunal; public class Ceiling { public static void main(String[] args) { int[] arr = {2, 3, 5, 9, 14, 16, 18}; int target = 15; int ans = ceiling(arr, target); System.out.println(ans); } // return the index of smallest no >= target static int ceiling(int[] arr, int target) { // but what if the target is greater than the greatest number in the array if (target > arr[arr.length - 1]) { return -1; } int start = 0; int end = arr.length - 1; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; } else if (target > arr[mid]) { start = mid + 1; } else { // ans found return mid; } } return start; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/FirstAndLastPosition.java ================================================ package com.kunal; public class FirstAndLastPosition { public static void main(String[] args) { } public int[] searchRange(int[] nums, int target) { int[] ans = {-1, -1}; // check for first occurrence if target first ans[0] = search(nums, target, true); if (ans[0] != -1) { ans[1] = search(nums, target, false); } return ans; } // this function just returns the index value of target int search(int[] nums, int target, boolean findStartIndex) { int ans = -1; int start = 0; int end = nums.length - 1; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < nums[mid]) { end = mid - 1; } else if (target > nums[mid]) { start = mid + 1; } else { // potential ans found ans = mid; if (findStartIndex) { end = mid - 1; } else { start = mid + 1; } } } return ans; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/Floor.java ================================================ package com.kunal; public class Floor { public static void main(String[] args) { int[] arr = {2, 3, 5, 9, 14, 16, 18}; int target = 1; int ans = floor(arr, target); System.out.println(ans); } // return the index: greatest number <= target static int floor(int[] arr, int target) { int start = 0; int end = arr.length - 1; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; } else if (target > arr[mid]) { start = mid + 1; } else { // ans found return mid; } } return end; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/InfiniteArray.java ================================================ package com.kunal; // https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/ public class InfiniteArray { public static void main(String[] args) { int[] arr = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int target = 10; System.out.println(ans(arr, target)); } static int ans(int[] arr, int target) { // first find the range // first start with a box of size 2 int start = 0; int end = 1; // condition for the target to lie in the range while (target > arr[end]) { int temp = end + 1; // this is my new start // double the box value // end = previous end + sizeofbox*2 end = end + (end - start + 1) * 2; start = temp; } return binarySearch(arr, target, start, end); } static int binarySearch(int[] arr, int target, int start, int end) { while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; } else if (target > arr[mid]) { start = mid + 1; } else { // ans found return mid; } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/Mountain.java ================================================ package com.kunal; public class Mountain { public static void main(String[] args) { } // https://leetcode.com/problems/peak-index-in-a-mountain-array/ // https://leetcode.com/problems/find-peak-element/ public int peakIndexInMountainArray(int[] arr) { int start = 0; int end = arr.length - 1; while (start < end) { int mid = start + (end - start) / 2; if (arr[mid] > arr[mid+1]) { // you are in dec part of array // this may be the ans, but look at left // this is why end != mid - 1 end = mid; } else { // you are in asc part of array start = mid + 1; // because we know that mid+1 element > mid element } } // in the end, start == end and pointing to the largest number because of the 2 checks above // start and end are always trying to find max element in the above 2 checks // hence, when they are pointing to just one element, that is the max one because that is what the checks say // more elaboration: at every point of time for start and end, they have the best possible answer till that time // and if we are saying that only one item is remaining, hence cuz of above line that is the best possible ans return start; // or return end as both are = } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/OrderAgnosticBS.java ================================================ package com.kunal; public class OrderAgnosticBS { public static void main(String[] args) { // int[] arr = {-18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89}; int[] arr = {99, 80, 75, 22, 11, 10, 5, 2, -3}; int target = 22; int ans = orderAgnosticBS(arr, target); System.out.println(ans); } static int orderAgnosticBS(int[] arr, int target) { int start = 0; int end = arr.length - 1; // find whether the array is sorted in ascending or descending boolean isAsc = arr[start] < arr[end]; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (arr[mid] == target) { return mid; } if (isAsc) { if (target < arr[mid]) { end = mid - 1; } else { start = mid + 1; } } else { if (target > arr[mid]) { end = mid - 1; } else { start = mid + 1; } } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/RBS.java ================================================ package com.kunal; // https://leetcode.com/problems/search-in-rotated-sorted-array/submissions/ public class RBS { public static void main(String[] args) { int[] arr = {1,2,3,4,5,5,6}; System.out.println(findPivotWithDuplicates(arr)); } static int search(int[] nums, int target) { int pivot = findPivot(nums); // if you did not find a pivot, it means the array is not rotated if (pivot == -1) { // just do normal binary search return binarySearch(nums, target, 0 , nums.length - 1); } // if pivot is found, you have found 2 asc sorted arrays if (nums[pivot] == target) { return pivot; } if (target >= nums[0]) { return binarySearch(nums, target, 0, pivot - 1); } return binarySearch(nums, target, pivot + 1, nums.length - 1); } static int binarySearch(int[] arr, int target, int start, int end) { while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < arr[mid]) { end = mid - 1; } else if (target > arr[mid]) { start = mid + 1; } else { // ans found return mid; } } return -1; } // this will not work in duplicate values static int findPivot(int[] arr) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = start + (end - start) / 2; // 4 cases over here if (mid < end && arr[mid] > arr[mid + 1]) { return mid; } if (mid > start && arr[mid] < arr[mid - 1]) { return mid-1; } if (arr[mid] <= arr[start]) { end = mid - 1; } else { start = mid + 1; } } return -1; } static int findPivotWithDuplicates(int[] arr) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = start + (end - start) / 2; // 4 cases over here if (mid < end && arr[mid] > arr[mid + 1]) { return mid; } if (mid > start && arr[mid] < arr[mid - 1]) { return mid-1; } // if elements at middle, start, end are equal then just skip the duplicates if (arr[mid] == arr[start] && arr[mid] == arr[end]) { // skip the duplicates // NOTE: what if these elements at start and end were the pivot?? // check if start is pivot if (start < end && arr[start] > arr[start + 1]) { return start; } start++; // check whether end is pivot if (end > start && arr[end] < arr[end - 1]) { return end - 1; } end--; } // left side is sorted, so pivot should be in right else if(arr[start] < arr[mid] || (arr[start] == arr[mid] && arr[mid] > arr[end])) { start = mid + 1; } else { end = mid - 1; } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/RotationCount.java ================================================ package com.kunal; public class RotationCount { public static void main(String[] args) { int[] arr = {4,5,6,7,0,1,2}; System.out.println(countRotations(arr)); } private static int countRotations(int[] arr) { int pivot = findPivot(arr); return pivot + 1; } // use this for non duplicates static int findPivot(int[] arr) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = start + (end - start) / 2; // 4 cases over here if (mid < end && arr[mid] > arr[mid + 1]) { return mid; } if (mid > start && arr[mid] < arr[mid - 1]) { return mid-1; } if (arr[mid] <= arr[start]) { end = mid - 1; } else { start = mid + 1; } } return -1; } // use this when arr contains duplicates static int findPivotWithDuplicates(int[] arr) { int start = 0; int end = arr.length - 1; while (start <= end) { int mid = start + (end - start) / 2; // 4 cases over here if (mid < end && arr[mid] > arr[mid + 1]) { return mid; } if (mid > start && arr[mid] < arr[mid - 1]) { return mid-1; } // if elements at middle, start, end are equal then just skip the duplicates if (arr[mid] == arr[start] && arr[mid] == arr[end]) { // skip the duplicates // NOTE: what if these elements at start and end were the pivot?? // check if start is pivot if (arr[start] > arr[start + 1]) { return start; } start++; // check whether end is pivot if (arr[end] < arr[end - 1]) { return end - 1; } end--; } // left side is sorted, so pivot should be in right else if(arr[start] < arr[mid] || (arr[start] == arr[mid] && arr[mid] > arr[end])) { start = mid + 1; } else { end = mid - 1; } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/RowColMatrix.java ================================================ package com.kunal; import java.util.Arrays; public class RowColMatrix { public static void main(String[] args) { int[][] arr = { {10, 20, 30, 40}, {15, 25, 35, 45}, {28, 29, 37, 49}, {33, 34, 38, 50} }; System.out.println(Arrays.toString(search(arr, 49))); } static int[] search(int[][] matrix, int target) { int r = 0; int c = matrix[0].length - 1; while (r < matrix.length && c >= 0) { if (matrix[r][c] == target) { return new int[]{r, c}; } if (matrix[r][c] < target) { r++; } else { c--; } } return new int[]{-1, -1}; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/SearchInMountain.java ================================================ package com.kunal; public class SearchInMountain { public static void main(String[] args) { } // https://leetcode.com/problems/find-in-mountain-array/ int search(int[] arr, int target) { int peak = peakIndexInMountainArray(arr); int firstTry = orderAgnosticBS(arr, target, 0, peak); if (firstTry != -1) { return firstTry; } // try to search in second half return orderAgnosticBS(arr, target, peak+1, arr.length - 1); } public int peakIndexInMountainArray(int[] arr) { int start = 0; int end = arr.length - 1; while (start < end) { int mid = start + (end - start) / 2; if (arr[mid] > arr[mid+1]) { // you are in dec part of array // this may be the ans, but look at left // this is why end != mid - 1 end = mid; } else { // you are in asc part of array start = mid + 1; // because we know that mid+1 element > mid element } } // in the end, start == end and pointing to the largest number because of the 2 checks above // start and end are always trying to find max element in the above 2 checks // hence, when they are pointing to just one element, that is the max one because that is what the checks say // more elaboration: at every point of time for start and end, they have the best possible answer till that time // and if we are saying that only one item is remaining, hence cuz of above line that is the best possible ans return start; // or return end as both are = } static int orderAgnosticBS(int[] arr, int target, int start, int end) { // find whether the array is sorted in ascending or descending boolean isAsc = arr[start] < arr[end]; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (arr[mid] == target) { return mid; } if (isAsc) { if (target < arr[mid]) { end = mid - 1; } else { start = mid + 1; } } else { if (target > arr[mid]) { end = mid - 1; } else { start = mid + 1; } } } return -1; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/SmallestLetter.java ================================================ package com.kunal; // https://leetcode.com/problems/find-smallest-letter-greater-than-target/ public class SmallestLetter { public static void main(String[] args) { } public char nextGreatestLetter(char[] letters, char target) { int start = 0; int end = letters.length - 1; while(start <= end) { // find the middle element // int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java int mid = start + (end - start) / 2; if (target < letters[mid]) { end = mid - 1; } else { start = mid + 1; } } return letters[start % letters.length]; } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/SortedMatrix.java ================================================ package com.kunal; import java.util.Arrays; public class SortedMatrix { public static void main(String[] args) { int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(Arrays.toString(search(arr, 9))); } // search in the row provided between the cols provided static int[] binarySearch(int[][] matrix, int row, int cStart, int cEnd, int target) { while (cStart <= cEnd) { int mid = cStart + (cEnd - cStart) / 2; if (matrix[row][mid] == target) { return new int[]{row, mid}; } if (matrix[row][mid] < target) { cStart = mid + 1; } else { cEnd = mid - 1; } } return new int[]{-1, -1}; } static int[] search(int[][] matrix, int target) { int rows = matrix.length; int cols = matrix[0].length; // be cautious, matrix may be empty if (cols == 0){ return new int[] {-1,-1}; } if (rows == 1) { return binarySearch(matrix,0, 0, cols-1, target); } int rStart = 0; int rEnd = rows - 1; int cMid = cols / 2; // run the loop till 2 rows are remaining while (rStart < (rEnd - 1)) { // while this is true it will have more than 2 rows int mid = rStart + (rEnd - rStart) / 2; if (matrix[mid][cMid] == target) { return new int[]{mid, cMid}; } if (matrix[mid][cMid] < target) { rStart = mid; } else { rEnd = mid; } } // now we have two rows // check whether the target is in the col of 2 rows if (matrix[rStart][cMid] == target) { return new int[]{rStart, cMid}; } if (matrix[rStart + 1][cMid] == target) { return new int[]{rStart + 1, cMid}; } // search in 1st half if (target <= matrix[rStart][cMid - 1]) { return binarySearch(matrix, rStart, 0, cMid-1, target); } // search in 2nd half if (target >= matrix[rStart][cMid + 1] && target <= matrix[rStart][cols - 1]) { return binarySearch(matrix, rStart, cMid + 1, cols - 1, target); } // search in 3rd half if (target <= matrix[rStart + 1][cMid - 1]) { return binarySearch(matrix, rStart + 1, 0, cMid-1, target); } else { return binarySearch(matrix, rStart + 1, cMid + 1, cols - 1, target); } } } ================================================ FILE: lectures/10-binary search/code/src/com/kunal/SplitArray.java ================================================ package com.kunal; // https://leetcode.com/problems/split-array-largest-sum/ public class SplitArray { public static void main(String[] args) { } public int splitArray(int[] nums, int m) { int start = 0; int end = 0; for (int i = 0; i < nums.length; i++) { start = Math.max(start, nums[i]); // in the end of the loop this will contain the max item of the array end += nums[i]; } // binary search while (start < end) { // try for the middle as potential ans int mid = start + (end - start) / 2; // calculate how many pieces you can divide this in with this max sum int sum = 0; int pieces = 1; for(int num : nums) { if (sum + num > mid) { // you cannot add this in this subarray, make new one // say you add this num in new subarray, then sum = num sum = num; pieces++; } else { sum += num; } } if (pieces > m) { start = mid + 1; } else { end = mid; } } return end; // here start == end } } ================================================ FILE: lectures/11-sorting/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/11-sorting/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/11-sorting/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/11-sorting/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/11-sorting/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/11-sorting/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/11-sorting/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/11-sorting/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/11-sorting/code/code.iml ================================================ ================================================ FILE: lectures/11-sorting/code/src/com/kunal/CyclicSort.java ================================================ package com.kunal; import java.util.Arrays; public class CyclicSort { public static void main(String[] args) { int[] arr = {5, 4, 3, 2, 1}; sort(arr); System.out.println(Arrays.toString(arr)); } static void sort(int[] arr) { int i = 0; while (i < arr.length) { int correct = arr[i] - 1; if (arr[i] != arr[correct]) { swap(arr, i , correct); } else { i++; } } } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/FindAllDuplicates.java ================================================ package com.kunal; import java.util.ArrayList; import java.util.List; // https://leetcode.com/problems/find-all-duplicates-in-an-array/ public class FindAllDuplicates { public List findDuplicates(int[] arr) { int i = 0; while (i < arr.length) { int correct = arr[i] - 1; if (arr[i] != arr[correct]) { swap(arr, i , correct); } else { i++; } } List ans = new ArrayList<>(); for (int index = 0; index < arr.length; index++) { if (arr[index] != index+1) { ans.add(arr[index]); } } return ans; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/FindAllMissing.java ================================================ package com.kunal; import java.util.ArrayList; import java.util.List; // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ // Asked in Google class FindAllMissing { public List findDisappearedNumbers(int[] nums) { int i = 0; while (i < nums.length) { int correct = nums[i] - 1; if (nums[i] != nums[correct]) { swap(nums, i , correct); } else { i++; } } // just find missing numbers List ans = new ArrayList<>(); for (int index = 0; index < nums.length; index++) { if (nums[index] != index+1) { ans.add(index + 1); } } return ans; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/FindDuplicate.java ================================================ package com.kunal; // https://leetcode.com/problems/find-the-duplicate-number/ public class FindDuplicate { public int findDuplicate(int[] arr) { int i = 0; while (i < arr.length) { if (arr[i] != i + 1) { int correct = arr[i] - 1; if (arr[i] != arr[correct]) { swap(arr, i , correct); } else { return arr[i]; } } else { i++; } } return -1; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/Main.java ================================================ package com.kunal; import java.util.Arrays; public class Main { public static void main(String[] args) { int[] arr = {5, 3, 4, 1, 2}; insertion(arr); System.out.println(Arrays.toString(arr)); } static void insertion(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = i+1; j > 0; j--) { if (arr[j] < arr[j-1]) { swap(arr, j, j-1); } else { break; } } } } static void selection(int[] arr) { for (int i = 0; i < arr.length; i++) { // find the max item in the remaining array and swap with correct index int last = arr.length - i - 1; int maxIndex = getMaxIndex(arr, 0, last); swap(arr, maxIndex, last); } } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } static int getMaxIndex(int[] arr, int start, int end) { int max = start; for (int i = start; i <= end; i++) { if (arr[max] < arr[i]) { max = i; } } return max; } static void bubble(int[] arr) { boolean swapped; // run the steps n-1 times for (int i = 0; i < arr.length; i++) { swapped = false; // for each step, max item will come at the last respective index for (int j = 1; j < arr.length - i; j++) { // swap if the item is smaller than the previous item if (arr[j] < arr[j-1]) { // swap int temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; swapped = true; } } // if you did not swap for a particular value of i, it means the array is sorted hence stop the program if (!swapped) { // !false = true break; } } } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/MissingNumber.java ================================================ package com.kunal; // https://leetcode.com/problems/missing-number/ // Amazon Question class MissingNumber { public static void main(String[] args) { int[] arr = {4, 0, 2, 1}; System.out.println(missingNumber(arr)); } public static int missingNumber(int[] arr) { int i = 0; while (i < arr.length) { int correct = arr[i]; if (arr[i] < arr.length && arr[i] != arr[correct]) { swap(arr, i , correct); } else { i++; } } // search for first missing number for (int index = 0; index < arr.length; index++) { if (arr[index] != index) { return index; } } // case 2 return arr.length; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/MissingPositive.java ================================================ package com.kunal; // https://leetcode.com/problems/first-missing-positive/ public class MissingPositive { public static int firstMissingPositive(int[] arr) { int i = 0; while (i < arr.length) { int correct = arr[i] - 1; if (arr[i] > 0 && arr[i] <= arr.length && arr[i] != arr[correct]) { swap(arr, i , correct); } else { i++; } } // search for first missing number for (int index = 0; index < arr.length; index++) { if (arr[index] != index + 1) { return index + 1; } } // case 2 return arr.length + 1; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/11-sorting/code/src/com/kunal/SetMismatch.java ================================================ package com.kunal; // https://leetcode.com/problems/set-mismatch/ public class SetMismatch { public int[] findErrorNums(int[] arr) { int i = 0; while (i < arr.length) { int correct = arr[i] - 1; if (arr[i] != arr[correct]) { swap(arr, i , correct); } else { i++; } } // search for first missing number for (int index = 0; index < arr.length; index++) { if (arr[index] != index + 1) { return new int[] {arr[index], index+1}; } } return new int[] {-1, -1}; } static void swap(int[] arr, int first, int second) { int temp = arr[first]; arr[first] = arr[second]; arr[second] = temp; } } ================================================ FILE: lectures/12-strings/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/12-strings/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/12-strings/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/12-strings/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/12-strings/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/12-strings/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/12-strings/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/12-strings/code/code.iml ================================================ ================================================ FILE: lectures/12-strings/code/src/com/kunal/Comparison.java ================================================ package com.kunal; public class Comparison { public static void main(String[] args) { String a = "Kunal"; String b = "Kunal"; String c = a; // System.out.println(c == a); // == // System.out.println(a == b); String name1 = new String("Kunal"); String name2 = new String("Kunal"); System.out.println(name1 == name2); System.out.println(name1.equals(name2)); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Main.java ================================================ package com.kunal; public class Main { public static void main(String[] args) { int[] arr = {2, 3, 5, 4, 19}; int num = 10; String name = "Kunal Kushwaha"; // System.out.println(name); String a = "Kunal"; System.out.println(a); a = "Kushwaha"; System.out.println(a); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Methods.java ================================================ package com.kunal; import java.util.Arrays; public class Methods { public static void main(String[] args) { String name = "Kunal Kushwaha Hello World"; System.out.println(Arrays.toString(name.toCharArray())); System.out.println(name.toLowerCase()); System.out.println(name); System.out.println(name.indexOf('a')); System.out.println(" Kunal ".strip()); System.out.println(Arrays.toString(name.split(" "))); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Operators.java ================================================ package com.kunal; import java.util.ArrayList; public class Operators { public static void main(String[] args) { System.out.println('a' + 'b'); System.out.println("a" + "b"); System.out.println((char)('a' + 3)); System.out.println("a" + 1); // this is same as after a few steps: "a" + "1" // integer will be converted to Integer that will call toString() System.out.println("Kunal" + new ArrayList<>()); System.out.println("Kunal" + new Integer(56)); String ans = new Integer(56) + "" + new ArrayList<>(); System.out.println(ans); System.out.println("a" + 'b'); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Output.java ================================================ package com.kunal; import java.util.Arrays; public class Output { public static void main(String[] args) { System.out.println(56); // Integer num = new Integer(56); // System.out.println(num.toString()); // System.out.println(num); // System.out.println("Kunal"); // System.out.println(Arrays.toString(new int[]{2, 3, 4, 5})); //// // String name = null; // System.out.println(name); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Palin.java ================================================ package com.kunal; public class Palin { public static void main(String[] args) { String str = "abcba"; System.out.println(isPalindrome(str)); } static boolean isPalindrome(String str) { if (str == null || str.length() == 0) { return true; } str = str.toLowerCase(); for (int i = 0; i <= str.length() / 2; i++) { char start = str.charAt(i); char end = str.charAt(str.length() - 1 - i); if (start != end) { return false; } } return true; } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/Performance.java ================================================ package com.kunal; public class Performance { public static void main(String[] args) { String series = ""; for (int i = 0; i < 26; i++) { char ch = (char)('a' + i); series = series + ch; // series += ch } System.out.println(series); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/PrettyPrinting.java ================================================ package com.kunal; public class PrettyPrinting { public static void main(String[] args) { float a = 453.1274f; // System.out.printf("Formatted number is %.2f", a); // System.out.printf("Pie: %.3f", Math.PI); System.out.printf("Hello my name is %s and I am %s", "Kunal", "Cool"); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/SB.java ================================================ package com.kunal; public class SB { public static void main(String[] args) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 26; i++) { char ch = (char)('a' + i); builder.append(ch); } System.out.println(builder.toString()); builder.reverse(); System.out.println(builder); } } ================================================ FILE: lectures/12-strings/code/src/com/kunal/placeholders_list.txt ================================================ There are many format specifiers we can use. Here are some common ones: %c - Character %d - Decimal number (base 10) %e - Exponential floating-point number %f - Floating-point number %i - Integer (base 10) %o - Octal number (base 8) %s - String %u - Unsigned decimal (integer) number %x - Hexadecimal number (base 16) %t - Date/time %n - Newline ================================================ FILE: lectures/13-patterns/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/13-patterns/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/13-patterns/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/13-patterns/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/13-patterns/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/13-patterns/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/13-patterns/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/13-patterns/code/code.iml ================================================ ================================================ FILE: lectures/13-patterns/code/src/com/kunal/Main.java ================================================ package com.kunal; public class Main { public static void main(String[] args) { pattern31(4); } static void pattern31(int n) { int originalN = n; n = 2 * n; for (int row = 0; row <= n; row++) { for (int col = 0; col <= n; col++) { int atEveryIndex = originalN - Math.min(Math.min(row, col), Math.min(n - row, n - col)); System.out.print(atEveryIndex + " "); } System.out.println(); } } static void pattern30(int n) { for (int row = 1; row <= n; row++) { for (int space = 0; space < n-row; space++) { System.out.print(" "); } for (int col = row; col >= 1; col--) { System.out.print(col + " "); } for (int col = 2; col <= row; col++) { System.out.print(col + " "); } System.out.println(); } } static void pattern17(int n) { for (int row = 1; row <= 2 * n; row++) { int c = row > n ? 2 * n - row: row; for (int space = 0; space < n-c; space++) { System.out.print(" "); } for (int col = c; col >= 1; col--) { System.out.print(col + " "); } for (int col = 2; col <= c; col++) { System.out.print(col + " "); } System.out.println(); } } static void pattern28(int n) { for (int row = 0; row < 2 * n; row++) { int totalColsInRow = row > n ? 2 * n - row: row; int noOfSpaces = n - totalColsInRow; for (int s = 0; s < noOfSpaces; s++) { System.out.print(" "); } for (int col = 0; col < totalColsInRow; col++) { System.out.print("* "); } System.out.println(); } } static void pattern5(int n) { for (int row = 0; row < 2 * n; row++) { int totalColsInRow = row > n ? 2 * n - row: row; for (int col = 0; col < totalColsInRow; col++) { System.out.print("* "); } System.out.println(); } } static void pattern4(int n) { for (int row = 1; row <= n; row++) { // for every row, run the col for (int col = 1; col <= row; col++) { System.out.print(col + " "); } // when one row is printed, we need to add a newline System.out.println(); } } static void pattern3(int n) { for (int row = 1; row <= n; row++) { // for every row, run the col for (int col = 1; col <= n-row+1; col++) { System.out.print("* "); } // when one row is printed, we need to add a newline System.out.println(); } } static void pattern1(int n) { for (int row = 1; row <= n; row++) { // for every row, run the col for (int col = 1; col <= n; col++) { System.out.print("* "); } // when one row is printed, we need to add a newline System.out.println(); } } static void pattern2(int n) { for (int row = 1; row <= n; row++) { // for every row, run the col for (int col = 1; col <= row; col++) { System.out.print("* "); } // when one row is printed, we need to add a newline System.out.println(); } } } ================================================ FILE: lectures/14-recursion/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/14-recursion/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/14-recursion/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/14-recursion/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/14-recursion/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/14-recursion/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/14-recursion/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/14-recursion/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/14-recursion/code/code.iml ================================================ ================================================ FILE: lectures/14-recursion/code/src/com/kunal/arrays/Find.java ================================================ package com.kunal.arrays; import java.util.ArrayList; public class Find { public static void main(String[] args) { int[] arr = {2, 3, 1, 4, 4, 5}; // System.out.println(find(arr, 4, 0)); // System.out.println(findIndex(arr, 4, 0)); // System.out.println(findIndexLast(arr, 4, arr.length-1)); // findAllIndex(arr, 4, 0); // System.out.println(list); // ArrayList list = new ArrayList<>(); // ArrayList ans = findAllIndex(arr, 4, 0, list); // System.out.println(ans); // System.out.println(list); System.out.println(findAllIndex2(arr, 4, 0)); } static boolean find(int[] arr, int target, int index) { if (index == arr.length) { return false; } return arr[index] == target || find(arr, target, index + 1); } static int findIndex(int[] arr, int target, int index) { if (index == arr.length) { return -1; } if (arr[index] == target) { return index; } else { return findIndex(arr, target, index + 1); } } static int findIndexLast(int[] arr, int target, int index) { if (index == -1) { return -1; } if (arr[index] == target) { return index; } else { return findIndexLast(arr, target, index - 1); } } static ArrayList list = new ArrayList<>(); static void findAllIndex(int[] arr, int target, int index) { if (index == arr.length) { return; } if (arr[index] == target) { list.add(index); } findAllIndex(arr, target, index + 1); } static ArrayList findAllIndex(int[] arr, int target, int index, ArrayList list) { if (index == arr.length) { return list; } if (arr[index] == target) { list.add(index); } return findAllIndex(arr, target, index + 1, list); } static ArrayList findAllIndex2(int[] arr, int target, int index) { ArrayList list = new ArrayList<>(); if (index == arr.length) { return list; } // this will contain answer for that function call only if (arr[index] == target) { list.add(index); } ArrayList ansFromBelowCalls = findAllIndex2(arr, target, index + 1); list.addAll(ansFromBelowCalls); return list; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/arrays/RBS.java ================================================ package com.kunal.arrays; public class RBS { public static void main(String[] args) { int[] arr = {5, 6, 7, 8, 9, 1, 2, 3}; System.out.println(search(arr, 4, 0, arr.length - 1)); } static int search(int[] arr, int target, int s, int e) { if (s > e) { return -1; } int m = s + (e-s) / 2; if (arr[m] == target) { return m; } if (arr[s] <= arr[m]) { if (target >= arr[s] && target <= arr[m]) { return search(arr, target, s, m-1); } else { return search(arr, target, m+1, e); } } if (target >= arr[m] && target <= arr[e]) { return search(arr, target, m+1, e); } return search(arr, target, s, m-1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/arrays/Sorted.java ================================================ package com.kunal.arrays; public class Sorted { public static void main(String[] args) { int[] arr = {1, 2, 3, 5, 16, 8}; System.out.println(sorted(arr, 0)); } static boolean sorted(int[] arr, int index) { // base condition if (index == arr.length - 1) { return true; } return arr[index] < arr[index + 1] && sorted(arr, index + 1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/backtracking/AllPaths.java ================================================ package com.kunal.backtracking; import java.util.Arrays; public class AllPaths { public static void main(String[] args) { boolean[][] board = { {true, true, true}, {true, true, true}, {true, true, true} }; int[][] path = new int[board.length][board[0].length]; allPathPrint("", board, 0, 0, path, 1); } static void allPath(String p, boolean[][] maze, int r, int c) { if (r == maze.length - 1 && c == maze[0].length - 1) { System.out.println(p); return; } if (!maze[r][c]) { return; } // i am considering this block in my path maze[r][c] = false; if (r < maze.length - 1) { allPath(p + 'D', maze, r+1, c); } if (c < maze[0].length - 1) { allPath(p + 'R', maze, r, c+1); } if (r > 0) { allPath(p + 'U', maze, r-1, c); } if (c > 0) { allPath(p + 'L', maze, r, c-1); } // this line is where the function will be over // so before the function gets removed, also remove the changes that were made by that function maze[r][c] = true; } static void allPathPrint(String p, boolean[][] maze, int r, int c, int[][] path, int step) { if (r == maze.length - 1 && c == maze[0].length - 1) { path[r][c] = step; for(int[] arr : path) { System.out.println(Arrays.toString(arr)); } System.out.println(p); System.out.println(); return; } if (!maze[r][c]) { return; } // i am considering this block in my path maze[r][c] = false; path[r][c] = step; if (r < maze.length - 1) { allPathPrint(p + 'D', maze, r+1, c, path, step+1); } if (c < maze[0].length - 1) { allPathPrint(p + 'R', maze, r, c+1, path, step+1); } if (r > 0) { allPathPrint(p + 'U', maze, r-1, c, path, step+1); } if (c > 0) { allPathPrint(p + 'L', maze, r, c-1, path, step+1); } // this line is where the function will be over // so before the function gets removed, also remove the changes that were made by that function maze[r][c] = true; path[r][c] = 0; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/backtracking/Maze.java ================================================ package com.kunal.backtracking; import java.util.ArrayList; public class Maze { public static void main(String[] args) { // System.out.println(count(3, 3)); // path("", 3, 3); // System.out.println(pathRet("", 3, 3)); // System.out.println(pathRetDiagonal("", 3, 3)); boolean[][] board = { {true, true, true}, {true, false, true}, {true, true, true} }; pathRestrictions("", board, 0, 0); } static int count(int r, int c) { if (r == 1 || c == 1) { return 1; } int left = count(r-1, c); int right = count(r, c-1); return left + right; } static void path(String p, int r, int c) { if (r == 1 && c == 1) { System.out.println(p); return; } if (r > 1) { path(p + 'D', r-1, c); } if (c > 1) { path(p + 'R', r, c-1); } } static ArrayList pathRet(String p, int r, int c) { if (r == 1 && c == 1) { ArrayList list = new ArrayList<>(); list.add(p); return list; } ArrayList list = new ArrayList<>(); if (r > 1) { list.addAll(pathRet(p + 'D', r-1, c)); } if (c > 1) { list.addAll(pathRet(p + 'R', r, c-1)); } return list; } static ArrayList pathRetDiagonal(String p, int r, int c) { if (r == 1 && c == 1) { ArrayList list = new ArrayList<>(); list.add(p); return list; } ArrayList list = new ArrayList<>(); if (r > 1 && c > 1) { list.addAll(pathRetDiagonal(p + 'D', r-1, c-1)); } if (r > 1) { list.addAll(pathRetDiagonal(p + 'V', r-1, c)); } if (c > 1) { list.addAll(pathRetDiagonal(p + 'H', r, c-1)); } return list; } static void pathRestrictions(String p, boolean[][] maze, int r, int c) { if (r == maze.length - 1 && c == maze[0].length - 1) { System.out.println(p); return; } if (!maze[r][c]) { return; } if (r < maze.length - 1) { pathRestrictions(p + 'D', maze, r+1, c); } if (c < maze[0].length - 1) { pathRestrictions(p + 'R', maze, r, c+1); } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/backtracking/NKnights.java ================================================ package com.kunal.backtracking; public class NKnights { public static void main(String[] args) { int n = 4; boolean[][] board = new boolean[n][n]; knight(board, 0, 0, 4); } static void knight(boolean[][] board, int row, int col, int knights) { if (knights == 0) { display(board); System.out.println(); return; } if (row == board.length - 1 && col == board.length) { return; } if (col == board.length) { knight(board, row + 1, 0, knights); return; } if (isSafe(board, row, col)) { board[row][col] = true; knight(board, row, col + 1, knights - 1); board[row][col] = false; } knight(board, row, col + 1, knights); } private static boolean isSafe(boolean[][] board, int row, int col) { if (isValid(board, row - 2, col - 1)) { if (board[row - 2][col - 1]) { return false; } } if (isValid(board, row - 1, col - 2)) { if (board[row - 1][col - 2]) { return false; } } if (isValid(board, row - 2, col + 1)) { if (board[row - 2][col + 1]) { return false; } } if (isValid(board, row - 1, col + 2)) { if (board[row - 1][col + 2]) { return false; } } return true; } // do not repeat yourself, hence created this function static boolean isValid(boolean[][] board, int row, int col) { if (row >= 0 && row < board.length && col >= 0 && col < board.length) { return true; } return false; } private static void display(boolean[][] board) { for(boolean[] row : board) { for(boolean element : row) { if (element) { System.out.print("K "); } else { System.out.print("X "); } } System.out.println(); } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/backtracking/NQueens.java ================================================ package com.kunal.backtracking; public class NQueens { public static void main(String[] args) { int n = 4; boolean[][] board = new boolean[n][n]; System.out.println(queens(board, 0)); } static int queens(boolean[][] board, int row) { if (row == board.length) { display(board); System.out.println(); return 1; } int count = 0; // placing the queen and checking for every row and col for (int col = 0; col < board.length; col++) { // place the queen if it is safe if(isSafe(board, row, col)) { board[row][col] = true; count += queens(board, row + 1); board[row][col] = false; } } return count; } private static boolean isSafe(boolean[][] board, int row, int col) { // check vertical row for (int i = 0; i < row; i++) { if (board[i][col]) { return false; } } // diagonal left int maxLeft = Math.min(row, col); for (int i = 1; i <= maxLeft; i++) { if(board[row-i][col-i]) { return false; } } // diagonal right int maxRight = Math.min(row, board.length - col - 1); for (int i = 1; i <= maxRight; i++) { if(board[row-i][col+i]) { return false; } } return true; } private static void display(boolean[][] board) { for(boolean[] row : board) { for(boolean element : row) { if (element) { System.out.print("Q "); } else { System.out.print("X "); } } System.out.println(); } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/backtracking/SudokuSolver.java ================================================ package com.kunal.backtracking; public class SudokuSolver { public static void main(String[] args) { int[][] board = new int[][]{ {3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, {0, 0, 5, 2, 0, 6, 3, 0, 0} }; if (solve(board)) { display(board); } else { System.out.println("Cannot solve"); } } static boolean solve(int[][] board) { int n = board.length; int row = -1; int col = -1; boolean emptyLeft = true; // this is how we are replacing the r,c from arguments for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; emptyLeft = false; break; } } // if you found some empty element in row, then break if (emptyLeft == false) { break; } } if (emptyLeft == true) { return true; // soduko is solved } // backtrack for (int number = 1; number <= 9; number++) { if (isSafe(board, row, col, number)) { board[row][col] = number; if (solve(board)) { // found the answer return true; } else { // backtrack board[row][col] = 0; } } } return false; } private static void display(int[][] board) { for(int[] row : board) { for(int num : row) { System.out.print(num + " "); } System.out.println(); } } static boolean isSafe(int[][] board, int row, int col, int num) { // check the row for (int i = 0; i < board.length; i++) { // check if the number is in the row if (board[row][i] == num) { return false; } } // check the col for (int[] nums : board) { // check if the number is in the col if (nums[col] == num) { return false; } } int sqrt = (int)(Math.sqrt(board.length)); int rowStart = row - row % sqrt; int colStart = col - col % sqrt; for (int r = rowStart; r < rowStart + sqrt; r++) { for (int c = colStart; c < colStart + sqrt; c++) { if (board[r][c] == num) { return false; } } } return true; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/CountZeros.java ================================================ package com.kunal.easy; public class CountZeros { public static void main(String[] args) { System.out.println(count(30210004)); } static int count(int n) { return helper(n, 0); } // special pattern, how to pass a value to above calls private static int helper(int n, int c) { if (n == 0) { return c; } int rem = n % 10; if (rem == 0) { return helper(n/10, c+1); } return helper(n/10, c); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/DigitProduct.java ================================================ package com.kunal.easy; public class DigitProduct { public static void main(String[] args) { int ans = prod(505); System.out.println(ans); } static int prod(int n) { if (n%10 == n) { return n; } return (n%10) * prod(n/10); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/DigitSum.java ================================================ package com.kunal.easy; public class DigitSum { public static void main(String[] args) { int ans = sum(1342); System.out.println(ans); } static int sum(int n) { if (n == 0) { return 0; } return (n % 10) + sum(n / 10); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Fact.java ================================================ package com.kunal.easy; public class Fact { public static void main(String[] args) { int ans = fact(5); System.out.println(ans); } static int fact(int n) { if (n <= 1) { return 1; } return n * fact(n-1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Nto1.java ================================================ package com.kunal.easy; public class Nto1 { public static void main(String[] args) { funBoth(5); } // concept static void concept(int n) { if (n == 0) { return; } System.out.println(n); // concept(n--); concept(--n); // n-- vs --n } static void fun(int n) { if (n == 0) { return; } System.out.println(n); fun(n-1); } static void funRev(int n) { if (n == 0) { return; } funRev(n-1); System.out.println(n); } static void funBoth(int n) { if (n == 0) { return; } System.out.println(n); funBoth(n-1); System.out.println(n); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Palindrome.java ================================================ package com.kunal.easy; public class Palindrome { static int rev(int n) { // sometimes you might need some additional variables in the argument // in that case, make another function int digits = (int)(Math.log10(n)) + 1; return helper(n, digits); } private static int helper(int n, int digits) { if (n%10 == n) { return n; } int rem = n % 10; return rem * (int)(Math.pow(10, digits-1)) + helper(n/10, digits-1); } static boolean palin(int n) { return n == rev(n); } public static void main(String[] args) { System.out.println(palin(1)); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Reverse.java ================================================ package com.kunal.easy; public class Reverse { static int sum = 0; static void rev1(int n) { if (n == 0) { return; } int rem = n % 10; sum = sum * 10 + rem; rev1(n/10); } static int rev2(int n) { // sometimes you might need some additional variables in the argument // in that case, make another function int digits = (int)(Math.log10(n)) + 1; return helper(n, digits); } private static int helper(int n, int digits) { if (n%10 == n) { return n; } int rem = n % 10; return rem * (int)(Math.pow(10, digits-1)) + helper(n/10, digits-1); } public static void main(String[] args) { System.out.println(rev2(1234)); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Steps.java ================================================ package com.kunal.easy; // https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero public class Steps { public static void main(String[] args) { } public int numberOfSteps(int num) { return helper(num, 0); } private int helper(int num, int steps) { if (num == 0) { return steps; } if (num % 2 == 0) { return helper(num/2, steps+1); } return helper(num-1, steps+1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/easy/Sum.java ================================================ package com.kunal.easy; public class Sum { public static void main(String[] args) { int ans = sum(5); System.out.println(ans); } static int sum(int n) { if (n <= 1) { return 1; } return n + sum(n-1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/intro/BS.java ================================================ package com.kunal.intro; public class BS { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 55, 66, 78}; int target = 78; System.out.println(search(arr, target, 0, arr.length - 1)); } static int search(int[] arr, int target, int s, int e) { if (s > e) { return -1; } int m = s + (e - s) / 2; if (arr[m] == target) { return m; } if (target < arr[m]) { return search(arr, target, s, m - 1); } return search(arr, target, m + 1, e); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/intro/Fibo.java ================================================ package com.kunal.intro; public class Fibo { public static void main(String[] args) { int ans = fibo(50); System.out.println(ans); } static int fibo(int n) { // base condition if (n < 2) { return n; } return fibo(n-1) + fibo(n-2); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/intro/Message.java ================================================ package com.kunal.intro; public class Message { public static void main(String[] args) { // write a function that prints hello world message(); } static void message() { System.out.println("Hello World"); message1(); } static void message1() { System.out.println("Hello World"); message2(); } static void message2() { System.out.println("Hello World"); message3(); } static void message3() { System.out.println("Hello World"); message4(); } static void message4() { System.out.println("Hello World"); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/intro/NumbersExample.java ================================================ package com.kunal.intro; public class NumbersExample { public static void main(String[] args) { // write a function that takes in a number and prints it // print first 5 numbers: 1 2 3 4 5 print1(1); } static void print1(int n) { System.out.println(n); print2(2); } static void print2(int n) { System.out.println(n); print3(3); } static void print3(int n) { System.out.println(n); print4(4); } static void print4(int n) { System.out.println(n); print5(5); } // func body here changes static void print5(int n) { System.out.println(n); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/intro/NumbersExampleRecursion.java ================================================ package com.kunal.intro; public class NumbersExampleRecursion { public static void main(String[] args) { // write a function that takes in a number and prints it // print first 5 numbers: 1 2 3 4 5 print(1); } static void print(int n) { // base condition if (n == 5) { System.out.println(5); return; } System.out.println(n); // recursive call // if you are calling a function again and again, you can treat it as a separate call in the stack // this is called tail recursion // this is the last function call print(n + 1); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/patterns/Triangle.java ================================================ package com.kunal.patterns; import java.util.Arrays; public class Triangle { public static void main(String[] args) { // triangle2(4, 0); int[] arr = {1, 4, 3, 5}; selection(arr, arr.length, 0, 0); System.out.println(Arrays.toString(arr)); } static void triangle2(int r, int c) { if (r == 0) { return; } if (c < r) { triangle2(r, c+1); System.out.print("*"); } else { triangle2(r-1, 0); System.out.println(); } } static void triangle(int r, int c) { if (r == 0) { return; } if (c < r) { System.out.print("*"); triangle(r, c+1); } else { System.out.println(); triangle(r-1, 0); } } static void bubble(int[] arr, int r, int c) { if (r == 0) { return; } if (c < r) { if (arr[c] > arr[c+1]) { // swap int temp = arr[c]; arr[c] = arr[c+1]; arr[c+1] = temp; } bubble(arr, r, c+1); } else { bubble(arr, r-1, 0); } } static void selection(int[] arr, int r, int c, int max) { if (r == 0) { return; } if (c < r) { if (arr[c] > arr[max]) { selection(arr, r, c+1, c); } else { selection(arr, r, c+1, max); } } else { int temp = arr[max]; arr[max] = arr[r-1]; arr[r-1] = temp; selection(arr, r-1, 0, 0); } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/sorting/MergeSort.java ================================================ package com.kunal.sorting; import java.util.Arrays; public class MergeSort { public static void main(String[] args) { int[] arr = {5, 4, 3, 2, 1}; mergeSortInPlace(arr, 0, arr.length); System.out.println(Arrays.toString(arr)); } static int[] mergeSort(int[] arr) { if (arr.length == 1) { return arr; } int mid = arr.length / 2; int[] left = mergeSort(Arrays.copyOfRange(arr, 0, mid)); int[] right = mergeSort(Arrays.copyOfRange(arr, mid, arr.length)); return merge(left, right); } private static int[] merge(int[] first, int[] second) { int[] mix = new int[first.length + second.length]; int i = 0; int j = 0; int k = 0; while (i < first.length && j < second.length) { if (first[i] < second[j]) { mix[k] = first[i]; i++; } else { mix[k] = second[j]; j++; } k++; } // it may be possible that one of the arrays is not complete // copy the remaining elements while (i < first.length) { mix[k] = first[i]; i++; k++; } while (j < second.length) { mix[k] = second[j]; j++; k++; } return mix; } static void mergeSortInPlace(int[] arr, int s, int e) { if (e - s == 1) { return; } int mid = (s + e) / 2; mergeSortInPlace(arr, s, mid); mergeSortInPlace(arr, mid, e); mergeInPlace(arr, s, mid, e); } private static void mergeInPlace(int[] arr, int s, int m, int e) { int[] mix = new int[e - s]; int i = s; int j = m; int k = 0; while (i < m && j < e) { if (arr[i] < arr[j]) { mix[k] = arr[i]; i++; } else { mix[k] = arr[j]; j++; } k++; } // it may be possible that one of the arrays is not complete // copy the remaining elements while (i < m) { mix[k] = arr[i]; i++; k++; } while (j < e) { mix[k] = arr[j]; j++; k++; } for (int l = 0; l < mix.length; l++) { arr[s+l] = mix[l]; } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/sorting/QuickSort.java ================================================ package com.kunal.sorting; import java.util.Arrays; public class QuickSort { public static void main(String[] args) { int[] arr = {5, 4, 3, 2, 1}; // sort(arr, 0, arr.length - 1); // System.out.println(Arrays.toString(arr)); Arrays.sort(arr); } static void sort(int[] nums, int low, int hi) { if (low >= hi) { return; } int s = low; int e = hi; int m = s + (e - s) / 2; int pivot = nums[m]; while (s <= e) { // also a reason why if its already sorted it will not swap while (nums[s] < pivot) { s++; } while (nums[e] > pivot) { e--; } if (s <= e) { int temp = nums[s]; nums[s] = nums[e]; nums[e] = temp; s++; e--; } } // now my pivot is at correct index, please sort two halves now sort(nums, low, e); sort(nums, s, hi); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/Ascii.java ================================================ package com.kunal.strings; public class Ascii { public static void main(String[] args) { char ch = 'a'; System.out.println((char)(ch + 1)); } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/Dice.java ================================================ package com.kunal.strings; import java.util.ArrayList; public class Dice { public static void main(String[] args) { dice("", 4); System.out.println(diceRet("", 4)); } static void dice(String p, int target) { if (target == 0) { System.out.println(p); return; } for (int i = 1; i <= 6 && i <= target; i++) { dice(p + i, target - i); } } static ArrayList diceRet(String p, int target) { if (target == 0) { ArrayList list = new ArrayList<>(); list.add(p); return list; } ArrayList list = new ArrayList<>(); for (int i = 1; i <= 6 && i <= target; i++) { list.addAll(diceRet(p + i, target - i)); } return list; } static void diceFace(String p, int target, int face) { if (target == 0) { System.out.println(p); return; } for (int i = 1; i <= face && i <= target; i++) { diceFace(p + i, target - i, face); } } static ArrayList diceFaceRet(String p, int target, int face) { if (target == 0) { ArrayList list = new ArrayList<>(); list.add(p); return list; } ArrayList list = new ArrayList<>(); for (int i = 1; i <= face && i <= target; i++) { list.addAll(diceFaceRet(p + i, target - i, face)); } return list; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/Permutations.java ================================================ package com.kunal.strings; import java.util.ArrayList; public class Permutations { public static void main(String[] args) { // permutations("", "abc"); // ArrayList ans = permutationsList("", "abc"); // System.out.println(ans); System.out.println(permutationsCount("", "abcd")); } static void permutations(String p, String up) { if (up.isEmpty()) { System.out.println(p); return; } char ch = up.charAt(0); for (int i = 0; i <= p.length(); i++) { String f = p.substring(0, i); String s = p.substring(i, p.length()); permutations(f + ch + s, up.substring(1)); } } static ArrayList permutationsList(String p, String up) { if (up.isEmpty()) { ArrayList list = new ArrayList<>(); list.add(p); return list; } char ch = up.charAt(0); // local to this call ArrayList ans = new ArrayList<>(); for (int i = 0; i <= p.length(); i++) { String f = p.substring(0, i); String s = p.substring(i, p.length()); ans.addAll(permutationsList(f + ch + s, up.substring(1))); } return ans; } static int permutationsCount(String p, String up) { if (up.isEmpty()) { return 1; } int count = 0; char ch = up.charAt(0); for (int i = 0; i <= p.length(); i++) { String f = p.substring(0, i); String s = p.substring(i, p.length()); count = count + permutationsCount(f + ch + s, up.substring(1)); } return count; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/PhonePad.java ================================================ package com.kunal.strings; import java.util.ArrayList; public class PhonePad { public static void main(String[] args) { System.out.println(padRet("", "12").size()); System.out.println(padCount("", "12")); } static void pad(String p, String up) { if (up.isEmpty()) { System.out.println(p); return; } int digit = up.charAt(0) - '0'; // this will convert '2' into 2 for (int i = (digit - 1) * 3; i < digit * 3; i++) { char ch = (char) ('a' + i); pad(p + ch, up.substring(1)); } } static ArrayList padRet(String p, String up) { if (up.isEmpty()) { ArrayList list = new ArrayList<>(); list.add(p); return list; } int digit = up.charAt(0) - '0'; // this will convert '2' into 2 ArrayList list = new ArrayList<>(); for (int i = (digit - 1) * 3; i < digit * 3; i++) { char ch = (char) ('a' + i); list.addAll(padRet(p + ch, up.substring(1))); } return list; } static int padCount(String p, String up) { if (up.isEmpty()) { return 1; } int count = 0; int digit = up.charAt(0) - '0'; // this will convert '2' into 2 for (int i = (digit - 1) * 3; i < digit * 3; i++) { char ch = (char) ('a' + i); count = count + padCount(p + ch, up.substring(1)); } return count; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/Stream.java ================================================ package com.kunal.strings; public class Stream { public static void main(String[] args) { System.out.println(skipAppNotApple("bacapplcdah")); } static void skip(String p, String up) { if (up.isEmpty()) { System.out.println(p); return; } char ch = up.charAt(0); if (ch == 'a') { skip(p, up.substring(1)); } else { skip(p + ch, up.substring(1)); } } static String skip(String up) { if (up.isEmpty()) { return ""; } char ch = up.charAt(0); if (ch == 'a') { return skip(up.substring(1)); } else { return ch + skip(up.substring(1)); } } static String skipApple(String up) { if (up.isEmpty()) { return ""; } if (up.startsWith("apple")) { return skipApple(up.substring(5)); } else { return up.charAt(0) + skipApple(up.substring(1)); } } static String skipAppNotApple(String up) { if (up.isEmpty()) { return ""; } if (up.startsWith("app") && !up.startsWith("apple")) { return skipAppNotApple(up.substring(3)); } else { return up.charAt(0) + skipAppNotApple(up.substring(1)); } } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/SubSeq.java ================================================ package com.kunal.strings; import java.util.ArrayList; public class SubSeq { public static void main(String[] args) { // subseqAscii("", "abc"); System.out.println(subseqAsciiRet("", "abc")); } static void subseq(String p, String up) { if (up.isEmpty()) { System.out.println(p); return; } char ch = up.charAt(0); subseq(p + ch, up.substring(1)); subseq(p, up.substring(1)); } static ArrayList subseqRet(String p, String up) { if (up.isEmpty()) { ArrayList list = new ArrayList<>(); list.add(p); return list; } char ch = up.charAt(0); ArrayList left = subseqRet(p + ch, up.substring(1)); ArrayList right = subseqRet(p, up.substring(1)); left.addAll(right); return left; } static void subseqAscii(String p, String up) { if (up.isEmpty()) { System.out.println(p); return; } char ch = up.charAt(0); subseqAscii(p + ch, up.substring(1)); subseqAscii(p, up.substring(1)); subseqAscii(p + (ch+0), up.substring(1)); } static ArrayList subseqAsciiRet(String p, String up) { if (up.isEmpty()) { ArrayList list = new ArrayList<>(); list.add(p); return list; } char ch = up.charAt(0); ArrayList first = subseqAsciiRet(p + ch, up.substring(1)); ArrayList second = subseqAsciiRet(p, up.substring(1)); ArrayList third = subseqAsciiRet(p + (ch+0), up.substring(1)); first.addAll(second); first.addAll(third); return first; } } ================================================ FILE: lectures/14-recursion/code/src/com/kunal/strings/SubSet.java ================================================ package com.kunal.strings; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SubSet { public static void main(String[] args) { int[] arr = {1, 2, 2}; List> ans = subsetDuplicate(arr); for (List list : ans) { System.out.println(list); } } static List> subset(int[] arr) { List> outer = new ArrayList<>(); outer.add(new ArrayList<>()); for (int num : arr) { int n = outer.size(); for (int i = 0; i < n; i++) { List internal = new ArrayList<>(outer.get(i)); internal.add(num); outer.add(internal); } } return outer; } static List> subsetDuplicate(int[] arr) { Arrays.sort(arr); List> outer = new ArrayList<>(); outer.add(new ArrayList<>()); int start = 0; int end = 0; for (int i = 0; i < arr.length; i++) { start = 0; // if current and previous element is same, s = e + 1 if (i > 0 && arr[i] == arr[i-1]) { start = end + 1; } end = outer.size() - 1; int n = outer.size(); for (int j = start; j < n; j++) { List internal = new ArrayList<>(outer.get(j)); internal.add(arr[i]); outer.add(internal); } } return outer; } } ================================================ FILE: lectures/15-complexity/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/15-complexity/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/15-complexity/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/15-complexity/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/15-complexity/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/15-complexity/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/15-complexity/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/15-complexity/code/code.iml ================================================ ================================================ FILE: lectures/15-complexity/code/src/com/kunal/Fibo.java ================================================ package com.kunal; public class Fibo { public static void main(String[] args) { // for (int i = 0; i < 11; i++) { // System.out.println(fiboFormula(i)); // } System.out.println(fiboFormula(50)); } static int fiboFormula(int n){ // just for demo, use long instead return (int) ((Math.pow(((1+Math.sqrt(5))/2),n)-Math.pow(((1-Math.sqrt(5))/2),n))/Math.sqrt(5)); } static int fibo(int n) { // base condition if (n < 2) { return n; } return fibo(n-1) + fibo(n-2); } } ================================================ FILE: lectures/16-math/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/16-math/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/16-math/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/16-math/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/16-math/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/16-math/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/16-math/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/16-math/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/16-math/code/code.iml ================================================ ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/FindUnique.java ================================================ package com.kunal.bitwise; public class FindUnique { public static void main(String[] args) { int[] arr = {2, 3, 3, 4, 2, 6, 4}; System.out.println(ans(arr)); } private static int ans(int[] arr) { int unique = 0; for(int n : arr) { unique ^= n; } return unique; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/FlipImage.java ================================================ package com.kunal.bitwise; // https://leetcode.com/problems/flipping-an-image class FlipImage { public int[][] flipAndInvertImage(int[][] image) { for(int[] row : image) { // reverse this array for (int i = 0; i < (image[0].length + 1) / 2; i++) { // swap int temp = row[i] ^ 1; row[i] = row[image[0].length - i - 1] ^ 1; row[image[0].length - i - 1] = temp; } } return image; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/MagicNumber.java ================================================ package com.kunal.bitwise; public class MagicNumber { public static void main(String[] args) { int n = 5; int ans = 0; int base = 5; while (n > 0) { int last = n & 1; n = n >> 1; ans += last * base; base = base * 5; } System.out.println(ans); } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/NoOfDigits.java ================================================ package com.kunal.bitwise; public class NoOfDigits { public static void main(String[] args) { int n = 10; int b = 2; int ans = (int)(Math.log(n) / Math.log(b)) + 1; System.out.println(ans); } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/OddEven.java ================================================ package com.kunal.bitwise; public class OddEven { public static void main(String[] args) { int n = 68; System.out.println(isOdd(n)); } private static boolean isOdd(int n) { return (n & 1) == 1; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/PowOfTwo.java ================================================ package com.kunal.bitwise; public class PowOfTwo { public static void main(String[] args) { int n = 31; // note: fix for n = 0 boolean ans = (n & (n-1)) == 0; System.out.println(ans); } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/Power.java ================================================ package com.kunal.bitwise; public class Power { public static void main(String[] args) { int base = 2; int power = 4; int ans = 1; while (power > 0) { if ((power & 1) == 1) { ans *= base; } base *= base; power = power >> 1; } System.out.println(ans); } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/RangeXOR.java ================================================ package com.kunal.bitwise; public class RangeXOR { public static void main(String[] args) { // range xor for a, b = xor(b) ^ xor(a-1) int a = 3; int b = 9; int ans = xor(b) ^ xor(a-1); System.out.println(ans); // only for check, will give TLE for large numbers int ans2 = 0; for (int i = a; i <= b; i++) { ans2 ^= i; } System.out.println(ans2); } // this gives xor from 0 to a static int xor(int a) { if (a % 4 == 0) { return a; } if (a % 4 == 1) { return 1; } if (a % 4 == 2) { return a + 1; } return 0; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/bitwise/SetBits.java ================================================ package com.kunal.bitwise; public class SetBits { public static void main(String[] args) { int n = 234567; System.out.println(Integer.toBinaryString(n)); System.out.println(setBits(n)); } private static int setBits(int n) { int count = 0; // while (n > 0) { // count++; // n -= (n & -n); // } while (n > 0) { count++; n = n & (n-1); } return count; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/BinarySearchSQRT.java ================================================ package com.kunal.maths; public class BinarySearchSQRT { public static void main(String[] args) { int n = 40; int p = 3; System.out.printf("%.3f", sqrt(n, p)); } // Time: O(log(n)) static double sqrt(int n, int p) { int s = 0; int e = n; double root = 0.0; while (s <= e) { int m = s + (e - s) / 2; if (m * m == n) { return m; } if (m * m > n) { e = m - 1; } else { s = m + 1; root = m; } } double incr = 0.1; for (int i = 0; i < p; i++) { while (root * root <= n) { root += incr; } root -= incr; incr /= 10; } return root; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/Factors.java ================================================ package com.kunal.maths; import java.util.ArrayList; public class Factors { public static void main(String[] args) { factors3(20); } // O(n) static void factors1(int n) { for (int i = 1; i <= n; i++) { if (n % i == 0) { System.out.print(i + " "); } } } // O(sqrt(n)) static void factors2(int n) { for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n/i == i) { System.out.print(i + " "); }else { System.out.print(i + " " + n/i + " "); } } } } // both time and space with be O(sqrt(n)) static void factors3(int n) { ArrayList list = new ArrayList<>(); for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n/i == i) { System.out.print(i + " "); }else { System.out.print(i + " "); list.add(n/i); } } } for (int i = list.size() - 1; i >= 0; i--) { System.out.print(list.get(i) + " "); } } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/GCD_LCM.java ================================================ package com.kunal.maths; public class GCD_LCM { public static void main(String[] args) { // System.out.println(gcd(4, 9)); System.out.println(lcm(2, 7)); } static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b%a, a); } static int lcm(int a, int b) { return a * b / gcd(a, b); } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/NewtonSQRT.java ================================================ package com.kunal.maths; public class NewtonSQRT { public static void main(String[] args) { System.out.println(sqrt(40)); } static double sqrt(double n) { double x = n; double root; while (true) { root = 0.5 * (x + (n/x)); if (Math.abs(root - x) < 0.5) { break; } x = root; } return root; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/Prime.java ================================================ package com.kunal.maths; public class Prime { public static void main(String[] args) { int n = 20; for (int i = 2; i <= n; i++) { System.out.println(i + " " + isPrime(i)); } } static boolean isPrime(int n) { if (n <= 1) { return false; } int c = 2; while (c * c <= n) { if (n % c == 0) { return false; } c++; } return true; } } ================================================ FILE: lectures/16-math/code/src/com/kunal/maths/Seive.java ================================================ package com.kunal.maths; public class Seive { public static void main(String[] args) { int n = 40; boolean[] primes = new boolean[n+1]; sieve(n, primes); } // false in array means number is prime static void sieve(int n, boolean[] primes) { for (int i = 2; i*i <= n; i++) { if (!primes[i]) { for (int j = i*2; j <= n; j+=i) { primes[j] = true; } } } for (int i = 2; i <= n; i++) { if (!primes[i]) { System.out.print(i + " "); } } } } ================================================ FILE: lectures/17-oop/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/17-oop/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/17-oop/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/17-oop/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/17-oop/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/17-oop/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/17-oop/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/17-oop/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/17-oop/code/code.iml ================================================ ================================================ FILE: lectures/17-oop/code/src/com/kunal/abstractDemo/Daughter.java ================================================ package com.kunal.abstractDemo; public class Daughter extends Parent{ public Daughter(int age) { super(age); } @Override void career() { System.out.println("I am going to be a coder"); } @Override void partner() { System.out.println("I love Iron Man"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/abstractDemo/Main.java ================================================ package com.kunal.abstractDemo; public class Main { public static void main(String[] args) { Son son = new Son(30); son.career(); son.normal(); Parent daughter = new Daughter(28); daughter.career(); Parent.hello(); // Parent mom = new Parent(45); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/abstractDemo/Parent.java ================================================ package com.kunal.abstractDemo; public abstract class Parent { int age; final int VALUE; public Parent(int age) { this.age = age; VALUE = 32456789; } static void hello(){ System.out.println("hey"); } void normal() { System.out.println("this is a normal method"); } abstract void career(); abstract void partner(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/abstractDemo/Parent2.java ================================================ package com.kunal.abstractDemo; public abstract class Parent2 { int age; final int VALUE; public Parent2(int age) { this.age = age; VALUE = 32456789; } static void hello(){ System.out.println("hey"); } void normal() { System.out.println("this is a normal method"); } abstract void career(); abstract void partner(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/abstractDemo/Son.java ================================================ package com.kunal.abstractDemo; public class Son extends Parent { public Son(int age) { super(age); } @Override void normal() { super.normal(); } @Override void career() { System.out.println("I am going to be a doctor"); } @Override void partner() { System.out.println("I love Pepper Potts"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/access/A.java ================================================ package com.kunal.access; public class A { protected int num; String name; int[] arr; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public A(int num, String name) { this.num = num; this.name = name; this.arr = new int[num]; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/access/Main.java ================================================ package com.kunal.access; import java.util.ArrayList; public class Main { public static void main(String[] args) { A obj = new A(10, "Kunal"); // need to do a few things // 1. access the data members // 2. modify the data members // ArrayList list = new ArrayList<>(23); // list.DEFAULT_CAPACITY; obj.getNum(); int n = obj.num; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/access/ObjectDemo.java ================================================ package com.kunal.access; public class ObjectDemo { int num; float gpa; public ObjectDemo(int num, float gpa) { this.num = num; this.gpa = gpa; } // already covered these 2 @Override public String toString() { return super.toString(); } @Override protected void finalize() throws Throwable { super.finalize(); } // we will go in details of how to create it in hashmap lecture @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return this.num == ((ObjectDemo)obj).num; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String[] args) { ObjectDemo obj1 = new ObjectDemo(12, 56.8f); ObjectDemo obj2 = new ObjectDemo(12, 78.9f); if (obj1 == obj2) { System.out.println("obj1 is equal to obj2"); } if (obj1.equals(obj2)) { System.out.println("obj1 is equal to obj2"); } System.out.println(obj1.getClass().getName()); // System.out.println(obj.hashCode()); // System.out.println(obj2.hashCode()); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/access/SubClass.java ================================================ package com.kunal.access; public class SubClass extends A{ public SubClass(int num, String name) { super(num, name); } public static void main(String[] args) { SubClass obj = new SubClass(45, "Kunal Kushwaha"); int n = obj.num; System.out.println(obj instanceof Object); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/cloning/Human.java ================================================ package com.kunal.cloning; public class Human implements Cloneable{ int age; String name; int[] arr; public Human(int age, String name) { this.age = age; this.name = name; this.arr = new int[]{3, 4, 5, 6, 9, 1}; } // @Override // public Object clone() throws CloneNotSupportedException{ // // this is shallow copy // return super.clone(); // } @Override public Object clone() throws CloneNotSupportedException{ // this is deep copy Human twin = (Human)super.clone(); // this is actually shallow copy // make a deep copy twin.arr = new int[twin.arr.length]; for (int i = 0; i < twin.arr.length; i++) { twin.arr[i] = this.arr[i]; } return twin; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/cloning/Main.java ================================================ package com.kunal.cloning; import java.util.Arrays; public class Main { public static void main(String[] args) throws CloneNotSupportedException { Human kunal = new Human(34, "Kunal Kushwaha"); // Human twin = new Human(kunal); Human twin = (Human)kunal.clone(); System.out.println(twin.age + " " + twin.name); System.out.println(Arrays.toString(twin.arr)); twin.arr[0] = 100; System.out.println(Arrays.toString(twin.arr)); System.out.println(Arrays.toString(kunal.arr)); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/collections/Main.java ================================================ package com.kunal.collections; import java.util.*; public class Main { public static void main(String[] args) { List list = new ArrayList<>(); List list2 = new LinkedList<>(); // list2.add(34); // list2.add(78); // list2.add(55); // list2.add(89); // // System.out.println(list2); List vector = new Vector<>(); vector.add(45); vector.add(5); vector.add(15); vector.add(56); System.out.println(vector); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/enumExamples/A.java ================================================ package com.kunal.enumExamples; public interface A { void hello(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/enumExamples/Basic.java ================================================ package com.kunal.enumExamples; public class Basic { enum Week implements A{ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; // these are enum constants // public, static and final // since its final you cannot create child enums // type is Week void display() { } Week() { System.out.println("Constructor called for " + this); } @Override public void hello() { System.out.println("hey how are you"); } // this is not public or protected, only private or default // why? we dont want to create new objects // this is not the enum concept, thats why // internally: public static final Week Monday = new Week(); } public static void main(String[] args) { Week week; week = Week.Monday; week.hello(); System.out.println(Week.valueOf("Monday")); // for(Week day : Week.values()) { // System.out.println(day); // } // System.out.println(week.ordinal()); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/exceptionHandling/Demo.java ================================================ package com.kunal.exceptionHandling; public class Demo { public static void main(String[] args) { Main.divide(3, 0); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/exceptionHandling/Main.java ================================================ package com.kunal.exceptionHandling; public class Main { public static void main(String[] args) { int a = 5; int b = 0; try { // divide(a, b); // mimicing String name = "Kunal"; if (name.equals("Kunal")) { throw new MyException("name is kunal"); } } catch (MyException e) { System.out.println(e.getMessage()); } catch (ArithmeticException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println("normal exception"); } finally { System.out.println("this will always execute"); } } static int divide(int a, int b) throws ArithmeticException{ if (b == 0) { throw new ArithmeticException("please do no divide by zero"); } return a / b; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/exceptionHandling/MyException.java ================================================ package com.kunal.exceptionHandling; public class MyException extends Exception{ public MyException(String message) { super(message); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/CustomArrayList.java ================================================ package com.kunal.generics; import java.util.ArrayList; import java.util.Arrays; public class CustomArrayList { private int[] data; private static int DEFAULT_SIZE = 10; private int size = 0; // also working as index value public CustomArrayList() { this.data = new int[DEFAULT_SIZE]; } public void add(int num) { if (isFull()) { resize(); } data[size++] = num; } private void resize() { int[] temp = new int[data.length * 2]; // copy the current items in the new array for (int i = 0; i < data.length; i++) { temp[i] = data[i]; } data = temp; } private boolean isFull() { return size == data.length; } public int remove() { int removed = data[--size]; return removed; } public int get(int index) { return data[index]; } public int size() { return size; } public void set(int index, int value) { data[index] = value; } @Override public String toString() { return "CustomArrayList{" + "data=" + Arrays.toString(data) + ", size=" + size + '}'; } public static void main(String[] args) { // ArrayList list = new ArrayList(); CustomArrayList list = new CustomArrayList(); // list.add(3); // list.add(5); // list.add(9); for (int i = 0; i < 14; i++) { list.add(2 * i); } System.out.println(list); ArrayList list2 = new ArrayList<>(); // list2.add("dfghj"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/CustomGenArrayList.java ================================================ package com.kunal.generics; import java.util.ArrayList; import java.util.Arrays; // https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects public class CustomGenArrayList { private Object[] data; private static int DEFAULT_SIZE = 10; private int size = 0; // also working as index value public CustomGenArrayList() { data = new Object[DEFAULT_SIZE]; } public void add(T num) { if (isFull()) { resize(); } data[size++] = num; } private void resize() { Object[] temp = new Object[data.length * 2]; // copy the current items in the new array for (int i = 0; i < data.length; i++) { temp[i] = data[i]; } data = temp; } private boolean isFull() { return size == data.length; } public T remove() { T removed = (T)(data[--size]); return removed; } public T get(int index) { return (T)data[index]; } public int size() { return size; } public void set(int index, T value) { data[index] = value; } @Override public String toString() { return "CustomGenArrayList{" + "data=" + Arrays.toString(data) + ", size=" + size + '}'; } public static void main(String[] args) { // ArrayList list = new ArrayList(); CustomGenArrayList list = new CustomGenArrayList(); // list.add(3); // list.add(5); // list.add(9); // for (int i = 0; i < 14; i++) { // list.add(2 * i); // } // System.out.println(list); ArrayList list2 = new ArrayList<>(); // list2.add("dfghj"); CustomGenArrayList list3 = new CustomGenArrayList<>(); for (int i = 0; i < 14; i++) { list3.add(2 * i); } System.out.println(list3); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/GenericInterface.java ================================================ package com.kunal.generics; public interface GenericInterface { void display(T value); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/LambdaFunctions.java ================================================ package com.kunal.generics; import java.util.ArrayList; import java.util.function.Consumer; public class LambdaFunctions { public static void main(String[] args) { ArrayList arr = new ArrayList<>(); for (int i = 0; i < 5; i++) { arr.add(i + 1); } // arr.forEach((item) -> System.out.println(item * 2)); Consumer fun = (item) -> System.out.println(item * 2); arr.forEach(fun); Operation sum = (a, b) -> a + b; Operation prod = (a, b) -> a * b; Operation sub = (a, b) -> a - b; LambdaFunctions myCalculator = new LambdaFunctions(); System.out.println(myCalculator.operate(5, 3, sum)); System.out.println(myCalculator.operate(5, 3, prod)); System.out.println(myCalculator.operate(5, 3, sub)); } private int operate(int a, int b, Operation op) { return op.operation(a, b); } } interface Operation { int operation(int a, int b); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/Main.java ================================================ package com.kunal.generics; public class Main implements GenericInterface{ @Override public void display(Integer value) { } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/WildcardExample.java ================================================ package com.kunal.generics; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects // here T should either be Number or its subclasses public class WildcardExample { private Object[] data; private static int DEFAULT_SIZE = 10; private int size = 0; // also working as inde value public WildcardExample() { data = new Object[DEFAULT_SIZE]; } public void getList(List list) { // do something } public void add(T num) { if (isFull()) { resize(); } data[size++] = num; } private void resize() { Object[] temp = new Object[data.length * 2]; // copy the current items in the new array for (int i = 0; i < data.length; i++) { temp[i] = data[i]; } data = temp; } private boolean isFull() { return size == data.length; } public T remove() { T removed = (T)(data[--size]); return removed; } public T get(int index) { return (T)data[index]; } public int size() { return size; } public void set(int index, T value) { data[index] = value; } @Override public String toString() { return "CustomGenArrayList{" + "data=" + Arrays.toString(data) + ", size=" + size + '}'; } public static void main(String[] args) { // ArrayList list = new ArrayList(); WildcardExample list = new WildcardExample(); // list.add(3); // list.add(5); // list.add(9); // for (int i = 0; i < 14; i++) { // list.add(2 * i); // } // System.out.println(list); ArrayList list2 = new ArrayList<>(); // list2.add("dfghj"); WildcardExample list3 = new WildcardExample<>(); for (int i = 0; i < 14; i++) { list3.add(2 * i); } System.out.println(list3); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/comparing/Main.java ================================================ package com.kunal.generics.comparing; import java.util.Arrays; import java.util.Comparator; public class Main { public static void main(String[] args) { Student kunal = new Student(12, 89.76f); Student rahul = new Student(5, 99.52f); Student arpit = new Student(2, 95.52f); Student karan = new Student(13, 77.52f); Student sachin = new Student(9, 96.52f); Student[] list = {kunal, rahul, arpit, karan, sachin}; System.out.println(Arrays.toString(list)); // Arrays.sort(list, new Comparator() { // @Override // public int compare(Student o1, Student o2) { // return -(int)(o1.marks - o2.marks); // } // }); Arrays.sort(list, (o1, o2) -> -(int)(o1.marks - o2.marks)); System.out.println(Arrays.toString(list)); // if (kunal.compareTo(rahul) < 0) { // System.out.println(kunal.compareTo(rahul)); // System.out.println("Rahul has more marks"); // } } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/generics/comparing/Student.java ================================================ package com.kunal.generics.comparing; public class Student implements Comparable{ int rollno; float marks; public Student(int rollno, float marks) { this.rollno = rollno; this.marks = marks; } @Override public String toString() { return marks + ""; } @Override public int compareTo(Student o) { System.out.println("in compareto method"); int diff = (int)(this.marks - o.marks); // if diff == 0: means both are equal // if diff < 0: means o is bigger else o is smaller return diff; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/Brake.java ================================================ package com.kunal.interfaces; public interface Brake { void brake(); // void start(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/CDPlayer.java ================================================ package com.kunal.interfaces; public class CDPlayer implements Media{ @Override public void start() { System.out.println("Music start"); } @Override public void stop() { System.out.println("Music stop"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/Car.java ================================================ package com.kunal.interfaces; public class Car implements Engine, Brake, Media{ int a = 30; @Override public void brake() { System.out.println("I brake like a normal Car"); } @Override public void start() { System.out.println("I start engine like a normal Car"); } @Override public void stop() { System.out.println("I stop engine like a normal Car"); } @Override public void acc() { System.out.println("I accelerate like a normal Car"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/ElecticEngine.java ================================================ package com.kunal.interfaces; public class ElecticEngine implements Engine{ @Override public void start() { System.out.println("Electric engine start"); } @Override public void stop() { System.out.println("Electric engine stop"); } @Override public void acc() { System.out.println("Electric engine accelerate"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/Engine.java ================================================ package com.kunal.interfaces; public interface Engine { static final int PRICE = 78000; void start(); void stop(); void acc(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/Main.java ================================================ package com.kunal.interfaces; public class Main { public static void main(String[] args) { // Engine car = new Car(); // car.a; // car.acc(); // car.start(); // car.stop(); // Media carMedia = new Car(); // carMedia.stop(); NiceCar car = new NiceCar(); car.start(); car.startMusic(); car.upgradeEngine(); car.start(); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/Media.java ================================================ package com.kunal.interfaces; public interface Media { void start(); void stop(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/NiceCar.java ================================================ package com.kunal.interfaces; public class NiceCar { private Engine engine; private Media player = new CDPlayer(); public NiceCar() { engine = new PowerEngine(); } public NiceCar(Engine engine) { this.engine = engine; } public void start() { engine.start(); } public void stop() { engine.stop(); } public void startMusic() { player.start(); } public void stopMusic() { player.stop(); } public void upgradeEngine() { this.engine = new ElecticEngine(); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/PowerEngine.java ================================================ package com.kunal.interfaces; public class PowerEngine implements Engine{ @Override public void start() { System.out.println("Power engine start"); } @Override public void stop() { System.out.println("Power engine stop"); } @Override public void acc() { System.out.println("Power engine accelerate"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo/A.java ================================================ package com.kunal.interfaces.extendDemo; public interface A { void fun(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo/B.java ================================================ package com.kunal.interfaces.extendDemo; public interface B extends A{ void greet(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo/Main.java ================================================ package com.kunal.interfaces.extendDemo; public class Main implements B{ @Override public void fun() { } @Override public void greet() { } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo2/A.java ================================================ package com.kunal.interfaces.extendDemo2; public interface A { // static interface methods should always have a body // call via the interface name static void greeting() { System.out.println("Hey I am static method"); } default void fun() { System.out.println("I am in A"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo2/B.java ================================================ package com.kunal.interfaces.extendDemo2; public interface B{ void greet(); // default void fun() { // System.out.println("I am in A"); // } // void fun(); } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/extendDemo2/Main.java ================================================ package com.kunal.interfaces.extendDemo2; public class Main implements A, B { @Override public void greet() { } public static void main(String[] args) { Main obj = new Main(); A.greeting(); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/nested/A.java ================================================ package com.kunal.interfaces.nested; public class A { // nested interface public interface NestedInterface { boolean isOdd(int num); } } class B implements A.NestedInterface { @Override public boolean isOdd(int num) { return (num & 1) == 1; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/interfaces/nested/Main.java ================================================ package com.kunal.interfaces.nested; public class Main { public static void main(String[] args) { B obj = new B(); System.out.println(obj.isOdd(6)); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/introduction/Main.java ================================================ package com.kunal.introduction; import java.sql.Struct; import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String[] args) { // store 5 roll nos int[] numbers = new int[5]; // store 5 names String[] names = new String[5]; // data of 5 students: {roll no, name, marks} int[] rno = new int[5]; String[] name = new String[5]; float[] marks = new float[5]; Student[] students = new Student[5]; // just declaring // Student kunal; // kunal = new Student(); Student kunal = new Student(15, "Kunal Kushwaha", 85.4f); Student rahul = new Student(18, "Rahul Rana", 90.3f); // kunal.rno = 13; // kunal.name = "Kunal Kushwaha"; // kunal.marks = 88.5f; // kunal.changeName("Shoe lover"); // kunal.greeting(); // System.out.println(kunal.rno); System.out.println(kunal.name); System.out.println(kunal.marks); Student random = new Student(kunal); System.out.println(random.name); Student random2 = new Student(); System.out.println(random2.name); Student one = new Student(); Student two = one; one.name = "Something something"; System.out.println(two.name); } } // create a class // for every single student class Student { int rno; String name; float marks = 90; // we need a way to add the values of the above // properties object by object // we need one word to access every object void greeting() { System.out.println("Hello! My name is " + this.name); } void changeName(String name) { this.name = name; } Student (Student other) { this.name = other.name; this.rno = other.rno; this.marks = other.marks; } Student () { // this is how you call a constructor from another constructor // internally: new Student (13, "default person", 100.0f); this (13, "default person", 100.0f); } // Student arpit = new Student(17, "Arpit", 89.7f); // here, this will be replaced with arpit Student (int rno, String name, float marks) { this.rno = rno; this.name = name; this.marks = marks; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/introduction/WrapperExample.java ================================================ package com.kunal.introduction; public class WrapperExample { public static void main(String[] args) { // int a = 10; // int b = 20; // // Integer num = 45; Integer a = 10; Integer b = 20; swap(a, b); System.out.println(a + " " + b); // final int bonus = 2; // bonus = 3; final A kunal = new A("Kunal Kushwaha"); kunal.name = "other name"; // when a non primitive is final, you cannot reassign it. // kunal = new A("new object"); A obj = new A("Rnadvsjhv"); System.out.println(obj); // for (int i = 0; i < 1000000000; i++) { // obj = new A("Random name"); // } } static void swap(Integer a, Integer b) { Integer temp = a; a = b; b = temp; } } class A { final int num = 10; String name; public A(String name) { // System.out.println("object created"); this.name = name; } @Override protected void finalize() throws Throwable { System.out.println("Object is destroyed"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/packages/a/Greeting.java ================================================ package com.kunal.packages.a; import static com.kunal.packages.b.Message.message; public class Greeting { public static void main(String[] args) { System.out.println("Hello world"); message(); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/packages/b/Greeting.java ================================================ package com.kunal.packages.b; public class Greeting { public static void main(String[] args) { System.out.println(" I am awesome"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/packages/b/Message.java ================================================ package com.kunal.packages.b; public class Message { public static void main(String[] args) { } public static void message() { System.out.println("This course is awesome"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/inheritance/Box.java ================================================ package com.kunal.properties.inheritance; public class Box { private double l; double h; double w; // double weight; static void greeting() { System.out.println("Hey, I am in Box class. Greetings!"); } public double getL() { return l; } Box () { this.h = -1; this.l = -1; this.w = -1; } // cube Box (double side) { // super(); Object class this.w = side; this.l = side; this.h = side; } Box(double l, double h, double w) { System.out.println("Box class constructor"); this.l = l; this.h = h; this.w = w; } Box(Box old) { this.h = old.h; this.l = old.l; this.w = old.w; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/inheritance/BoxColor.java ================================================ package com.kunal.properties.inheritance; public class BoxColor extends BoxWeight { } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/inheritance/BoxPrice.java ================================================ package com.kunal.properties.inheritance; public class BoxPrice extends BoxWeight{ double cost; BoxPrice () { super(); this.cost = -1; } BoxPrice(BoxPrice other) { super(other); this.cost = other.cost; } public BoxPrice(double l, double h, double w, double weight, double cost) { super(l, h, w, weight); this.cost = cost; } public BoxPrice(double side, double weight, double cost) { super(side, weight); this.cost = cost; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/inheritance/BoxWeight.java ================================================ package com.kunal.properties.inheritance; import java.util.ArrayList; public class BoxWeight extends Box{ double weight; public BoxWeight() { this.weight = -1; } // @Override static void greeting() { System.out.println("Hey, I am in BoxWeight class. Greetings!"); ArrayList list = new ArrayList(); } BoxWeight (BoxWeight other) { super(other); weight = other.weight; } BoxWeight(double side, double weight) { super(side); this.weight = weight; } public BoxWeight(double l, double h, double w, double weight) { // used to initialise values present in parent class super(l, h, w); // what is this? call the parent class constructor // System.out.println(super.weight); this.weight = weight; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/inheritance/Main.java ================================================ package com.kunal.properties.inheritance; public class Main { public static void main(String[] args) { Box box1 = new Box(4.6, 7.9, 9.9); box1.getL(); Box box2 = new Box(box1); // System.out.println(box1.w + " " + box1.h); // BoxWeight box3 = new BoxWeight(); // BoxWeight box4 = new BoxWeight(2, 3, 4, 8); // System.out.println(box3.h + " " + box3.weight); // Box box5 = new BoxWeight(2, 3, 4, 8); // System.out.println(box5.w); // there are many variables in both parent and child classes // you are given access to variables that are in the ref type i.e. BoxWeight // hence, you should have access to weight variable // this also means, that the ones you are trying to access should be initialised // but here, when the obj itself is of type parent class, how will you call the constructor of child class // this is why error // BoxWeight box6 = new Box(2, 3, 4); // System.out.println(box6); // Box.greeting(); BoxWeight box = new BoxWeight(); BoxWeight.greeting(); // you can inherit but you cannot override } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Circle.java ================================================ package com.kunal.properties.polymorphism; public class Circle extends Shapes{ // this will run when obj of Circle is created // hence it is overriding the parent method @Override // this is called annotation void area() { System.out.println("Area is pi * r * r"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Main.java ================================================ package com.kunal.properties.polymorphism; public class Main { public static void main(String[] args) { Shapes shape = new Shapes(); Shapes circle = new Circle(); Shapes square = new Square(); circle.area(); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Numbers.java ================================================ package com.kunal.properties.polymorphism; public class Numbers { double sum(double a, int b) { return a + b; } double sum(int a, int b) { return a + b; } int sum(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { Numbers obj = new Numbers(); obj.sum(2, 3); obj.sum(1, 3, 7); // obj.sum(4, 5, 6, 8); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/ObjectPrint.java ================================================ package com.kunal.properties.polymorphism; public class ObjectPrint { int num; public ObjectPrint(int num) { this.num = num; } @Override public String toString() { return "ObjectPrint{" + "num=" + num + '}'; } public static void main(String[] args) { ObjectPrint obj = new ObjectPrint(54); System.out.println(obj); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Shapes.java ================================================ package com.kunal.properties.polymorphism; public class Shapes { void area() { System.out.println("I am in shapes"); } // Early binding: check notes // final void area() { // System.out.println("I am in shapes"); // } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Square.java ================================================ package com.kunal.properties.polymorphism; public class Square extends Shapes{ void area() { System.out.println("Area is square of side"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/properties/polymorphism/Triangle.java ================================================ package com.kunal.properties.polymorphism; public class Triangle extends Shapes{ void area() { System.out.println("Area is 0.5 * h * b"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/singleton/Main.java ================================================ package com.kunal.singleton; import com.kunal.access.A; public class Main { public static void main(String[] args) { Singleton obj1 = Singleton.getInstance(); Singleton obj2 = Singleton.getInstance(); Singleton obj3 = Singleton.getInstance(); // all 3 ref variables are pointing to just one object A a = new A(10, "Kunal"); a.getNum(); // int n = a.num; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/singleton/NotSubClass.java ================================================ package com.kunal.singleton; import com.kunal.access.A; public class NotSubClass{ public static void main(String[] args) { NotSubClass obj = new NotSubClass(); // int n = obj.num; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/singleton/Singleton.java ================================================ package com.kunal.singleton; import com.kunal.access.A; public class Singleton { private Singleton () { } private static Singleton instance; public static Singleton getInstance() { // check whether 1 obj only is created or not if (instance == null) { instance = new Singleton(); } return instance; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/singleton/SubClass.java ================================================ package com.kunal.singleton; import com.kunal.access.A; import java.util.ArrayList; import java.util.Collections; public class SubClass extends A { public SubClass(int num, String name) { super(num, name); } public static void main(String[] args) { A obj = new A(45, "Kunal Kushwaha"); // int n = obj.num; } } class SubSubclass extends SubClass { public SubSubclass(int num, String name) { super(num, name); } public static void main(String[] args) { SubSubclass obj = new SubSubclass(45, "Kunal Kushwaha"); int n = obj.num; } } class SubClass2 extends A { public SubClass2(int num, String name) { super(num, name); } public static void main(String[] args) { SubClass2 obj = new SubClass2(45, "Kunal Kushwaha"); // int n = obj.num; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/staticExample/Human.java ================================================ package com.kunal.staticExample; public class Human { int age; String name; int salary; boolean married; static long population; static void message() { System.out.println("Hello world"); // System.out.println(this.age); // cant use this over here } public Human(int age, String name, int salary, boolean married) { this.age = age; this.name = name; this.salary = salary; this.married = married; Human.population += 1; } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/staticExample/InnerClasses.java ================================================ package com.kunal.staticExample; import java.util.Arrays; public class InnerClasses { static class Test { String name; public Test(String name) { this.name = name; } @Override public String toString() { return name; } } public static void main(String[] args) { Test a = new Test("Kunal"); Test b = new Test("Rahul"); System.out.println(a); // System.out.println(a.name); // System.out.println(b.name); } } //static class A { // //} ================================================ FILE: lectures/17-oop/code/src/com/kunal/staticExample/Main.java ================================================ package com.kunal.staticExample; public class Main { public static void main(String[] args) { // Human kunal = new Human(22, "Kunal", 10000, false); // Human rahul = new Human(34, "Rahul", 15000, true); // Human arpit = new Human(34, "arpit", 15000, true); // // System.out.println(Human.population); // System.out.println(Human.population); // System.out.println(Human.population); Main funn = new Main(); funn.fun2(); } // this is not dependent on objects static void fun() { // greeting(); // you cant use this because it requires an instance // but the function you are using it in does not depend on instances // you cannot access non static stuff without referencing their instances in // a static context // hence, here I am referencing it Main obj = new Main(); obj.greeting(); } void fun2() { greeting(); } // we know that something which is not static, belongs to an object void greeting() { // fun(); System.out.println("Hello world"); } } ================================================ FILE: lectures/17-oop/code/src/com/kunal/staticExample/StaticBlock.java ================================================ package com.kunal.staticExample; // this is a demo to show initialisation of static variables public class StaticBlock { static int a = 4; static int b; // will only run once, when the first obj is create i.e. when the class is loaded for the first time static { System.out.println("I am in static block"); b = a * 5; } public static void main(String[] args) { StaticBlock obj = new StaticBlock(); System.out.println(StaticBlock.a + " " + StaticBlock.b); StaticBlock.b += 3; System.out.println(StaticBlock.a + " " + StaticBlock.b); StaticBlock obj2 = new StaticBlock(); System.out.println(StaticBlock.a + " " + StaticBlock.b); } } ================================================ FILE: lectures/17-oop/notes/abstract.txt ================================================ Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. You may have methods that must be overridden by the subclass in order for the subclass to have any meaning. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java’s solution to this problem is the abstract method. You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. abstract type name(parameter-list); These methods are sometimes referred to as subclass's responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. Any class that contains one or more abstract methods must also be declared abstract. # There can be no objects of an abstract class. # You cannot declare abstract constructors, or abstract static methods. # You can declare static methods in abstract class. Because there can be no objects for abstract class. If they had allowed to call abstract static methods, it would that mean we are calling an empty method (abstract) through classname because it is static. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be declared abstract itself. Abstract classes can include as much implementation as they see fit i.e.there can be concrete methods(methods with body) in abstract class. Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of superclass references. A public constructor on an abstract class doesn't make any sense because you can't instantiate an abstract class directly (can only instantiate through a derived type that itself is not marked as abstract) Check: https://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor Abstract class vs Interface: Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc. ================================================ FILE: lectures/17-oop/notes/access_control.txt ================================================ Access Control: How a member can be accessed is determined by the access modifier attached to its declaration. Usually, you will want to restrict access to the data members of a class—allowing access only through methods. Also, there will be times when you will want to define methods that are private to a class. Java’s access modifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. When no access modifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. │ Class │ Package │ Subclass │ Subclass │ World │ │ │(same pkg)│(diff pkg)│(diff pkg & not subclass) ────────────┼───────┼─────────┼──────────┼──────────┼────────────────────────── public │ + │ + │ + │ + │ + ────────────┼───────┼─────────┼──────────┼──────────┼────────────────────────── protected │ + │ + │ + │ + │ ────────────┼───────┼─────────┼──────────┼──────────┼────────────────────────── no modifier │ + │ + │ + │ │ ────────────┼───────┼─────────┼──────────┼──────────┼────────────────────────── private │ + │ │ │ │ + : accessible blank : not accessible package packageOne; public class Base { protected void display(){ System.out.println("in Base"); } } package packageTwo; public class Derived extends packageOne.Base{ public void show(){ new Base().display(); // this is not working new Derived().display(); // is working display();//is working } } protected allows access from subclasses and from other classes in the same package. We can use child class to use protected member outside the package but only child class object can access it. That's why any Derived class instance can access the protected method in Base. The other line creates a Base instance (not a Derived instance!!). And access to protected methods of that instance is only allowed from objects of the same package. display(); -> allowed, because the caller, an instance of Derived has access to protected members and fields of its subclasses, even if they're in different packages new Derived().display(); -> allowed, because you call the method on an instance of Derived and that instance has access to the protected methods of its subclasses new Base().display(); -> not allowed because the caller's (the this instance) class is not defined in the same package like the Base class, so this can't access the protected method. And it doesn't matter - as we see - that the current subclasses a class from that package. That backdoor is closed ;) Remember that any time talks about a subclass having an access to a superclass member, we could be talking about the subclass inheriting the member, not simple accessing the member through a reference to an instance of the superclass. class C protected member; // in a different package class S extends C obj.member; // only allowed if type of obj is S or subclass of S The motivation is probably as following. If obj is an S, class S has sufficient knowledge of its internals, it has the right to manipulate its members, and it can do this safely. If obj is not an S, it's probably another subclass S2 of C, which S has no idea of. S2 may have not even been born when S is written. For S to manipulate S2's protected internals is quite dangerous. If this is allowed, from S2's point of view, it doesn't know who will tamper with its protected internals and how, this makes S2 job very hard to reason about its own state. Now if obj is D, and D extends S, is it dangerous for S to access obj.member? Not really. How S uses member is a shared knowledge of S and all its subclasses, including D. S as the superclass has the right to define behaviours, and D as the subclass has the obligation to accept and conform. For easier understanding, the rule should really be simplified to require obj's (static) type to be exactly S. After all, it's very unusual and inappropriate for subclass D to appear in S. And even if it happens, that the static type of obj is D, our simplified rule can deal with it easily by upcasting: ((S)obj).member ================================================ FILE: lectures/17-oop/notes/classes.txt ================================================ A class is a template for an object, and an object is an instance of a class. A class creates a new data type that can be used to create objects. When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality. (That is, an object occupies space in memory.) Objects are characterized by three essential properties: state, identity, and behavior. The state of an object is a value from its data type. The identity of an object distinguishes one object from another. It is useful to think of an object’s identity as the place where its value is stored in memory. The behavior of an object is the effect of data-type operations. The dot operator links the name of the object with the name of an instance variable. Although commonly referred to as the dot operator, the formal specification for Java categorizes the . as a separator. The 'new' keyword dynamically allocates(that is, allocates at run time)memory for an object & returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object The first line declares mybox as a reference to an object of type Box. At this point, mybox does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to mybox. After the second line executes, you can use mybox as if it were a Box object. But in reality, mybox simply holds, in essence, the memory address of the actual Box object. The key to Java’s safety is that you cannot manipulate references as you can actual pointers. Thus, you cannot cause an object reference to point to an arbitrary memory location or manipulate it like an integer. A Closer Look at new: classname class-var = new classname ( ); Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. You might be wondering why you do not need to use new for such things as integers or characters. The answer is that Java’s primitive types are not implemented as objects. Rather, they are implemented as “normal” variables. This is done in the interest of efficiency. It is important to understand that new allocates memory for an object during run time. Box b1 = new Box(); Box b2 = b1; b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference. int square(int i){ return i * i; } A parameter is a variable defined by a method that receives a value when the method is called. For example, in square( int i), i is a parameter. An argument is a value that is passed to a method when it is invoked. For example, square(100) passes 100 as an argument. Inside square( ), the parameter i receives that value. NOTE: Bus bus = new Bus(); lhs(reference i.e. bus) is looked by compiler & rhs (object i.e. new Bus()) is looked by jvm ================================================ FILE: lectures/17-oop/notes/constructors_this_finalize.txt ================================================ The this Keyword: Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. final Keyword: A field can be declared as final. Doing so prevents its contents from being modified, making it, essentially, a constant. This means that you must initialize a final field when it is declared. It is a common coding convention to choose all uppercase identifiers for final fields: final int FILE_OPEN = 2; Unfortunately, final guarantees immutability only when instance variables are primitive types, not reference types. If an instance variable of a reference type has the final modifier, the value of that instance variable (the reference to an object) will never change—it will always refer to the same object—but the value of the object itself can change. The finalize( ) Method: Sometimes an object will need to perform some action when it is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Right before an asset is freed, the Java run time calls the finalize( ) method on the object. protected void finalize( ) { // finalization code here } Constructors: Once defined, the constructor is automatically called when the object is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. In the line Box mybox1 = new Box(); new Box( ) is calling the Box( ) constructor. Inheritance and constructors in Java: In Java, constructor of base class with no argument gets automatically called in derived class constructor. For example, output of following program given below is: Base Class Constructor Called Derived Class Constructor Called // filename: Main.java class Base { Base() { System.out.println("Base Class Constructor Called "); } } class Derived extends Base { Derived() { System.out.println("Derived Class Constructor Called "); } } public class Main { public static void main(String[] args) { Derived d = new Derived(); } } Any class will have a default constructor, does not matter if we declare it in the class or not. If we inherit a class, then the derived class must call its super class constructor. It is done by default in derived class. If it does not have a default constructor in the derived class, the JVM will invoke its default constructor and call the super class constructor by default. If we have a parameterised constructor in the derived class still it calls the default super class constructor by default. In this case, if the super class does not have a default constructor, instead it has a parameterised constructor, then the derived class constructor should call explicitly call the parameterised super class constructor. ================================================ FILE: lectures/17-oop/notes/inheritance.txt ================================================ To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. class subclass-name extends superclass-name { // body of class } You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass. You can, as stated, create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself. Although a subclass includes all of the members of its superclass, it cannot access those members of the superclass that have been declared as private. A Superclass Variable Can Reference a Subclass Object: It is important to understand that it is the type of the reference variable—not the type of the object that it refers to—that determines what members can be accessed. When a reference to a subclass object is assigned to a superclass reference variable, you will have access only to those parts of the object defined by the superclass. plainbox = weightbox; (superclass) (subclass) SUPERCLASS ref = new SUBCLASS(); // HERE ref can only access methods which are available in SUPERCLASS Using super: Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass’ constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This causes the Box constructor to be called, which initializes width, height, and depth using these values. BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to it: weight. This leaves Box free to make these values private if desired. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy. class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } } class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } } Notice that super() is passed an object of type BoxWeight—not of type Box.This still invokes the constructor Box(Box ob). NOTE: A superclass variable can be used to reference any object derived from that class. Thus, we are able to pass a BoxWeight object to the Box constructor.Of course,Box only has knowledge of its own members. A Second Use for super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. super( ) always refers to the constructor in the closest superclass. The super( ) in BoxPrice calls the constructor in BoxWeight. The super( ) in BoxWeight calls the constructor in Box. In a class hierarchy, if a superclass constructor requires parameters, then all subclasses must pass those parameters “up the line.” This is true whether or not a subclass needs parameters of its own. If you think about it, it makes sense that constructors complete their execution in order of derivation. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must complete its execution first. NOTE: If super( ) is not used in subclass' constructor, then the default or parameterless constructor of each superclass will be executed. Using final with Inheritance: The keyword final has three uses: # First, it can be used to create the equivalent of a named constant. # Using final to Prevent Overriding: To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. Methods declared as final can sometimes provide a performance enhancement: The compiler is free to inline calls to them because it “knows” they will not be overridden by a subclass. When a small final method is called, often the Java compiler can copy the bytecode for the subroutine directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method call. Inlining is an option only with final methods. Normally, Java resolves calls to methods dynamically, at run time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding. # Using final to Prevent Inheritance: Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. NOTE: Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself & relies upon its subclasses to provide complete implementations. # NOTE: Although static methods can be inherited ,there is no point in overriding them in child classes because the method in parent class will run always no matter from which object you call it. That is why static interface methods cannot be inherited because these method will run from the parent interface and no matter if we were allowed to override them, they will always run the method in parent interface. That is why static interface method must have a body. NOTE : Polymorphism does not apply to instance variables. ================================================ FILE: lectures/17-oop/notes/interface.txt ================================================ Multiple inheritance is not available in java. (Same functions in 2 classes it will skip that hence no multiple inheritance) Instead we have java interfaces. they have abstract functions (no body of functions) Interface is like class but not completely. it is like an abstract class. By default functions are public and abstract in interface. variables are final and static by default in interface. Interfaces specify only what the class is doing, not how it is doing it. The problem with MULTIPLE INHERITANCE is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick. Key difference between a class and an interface: a class can maintain state information (especially through the use of instance variables), but an interface cannot. Using interface, you can specify a set of methods that can be implemented by one or more classes. Although they are similar to abstract classes, interfaces have an additional capability: A class can implement more than one interface. By contrast, a class can only inherit a single superclass (abstract or otherwise). Using the keyword interface, you can fully abstract a class’ interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and, as a general rule, their methods are declared without any body. By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect of polymorphism. NOTE: Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the Java compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and nonextensible classing environment. Inevitably in a system like this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface. This is where the real power of interfaces is realized. Beginning with JDK 8, it is possible to add a default implementation to an interface method. Thus, it is now possible for interface to specify some behavior.However, default methods constitute what is, in essence, a special-use feature, and the original intent behind interface still remains. Variables can be declared inside of interface declarations. NOTE: They are implicitly final and static, meaning they cannot be changed by the implementing class. They must also be initialized. All methods and variables are implicitly public. NOTE: The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition. It is both permissible and common for classes that implement interfaces to define additional members of their own. NOTE: You can declare variables as object references that use an interface rather than a class type. This process is similar to using a superclass reference to access a subclass object. Any instance of any class that implements the declared interface can be referred to by such a variable. When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to. Called at run time by the type of object it refers to. The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them. The calling code can dispatch through an interface without having to know anything about the “callee.” CAUTION: Because dynamic lookup of a method at run time incurs a significant overhead when compared with the normal method invocation in Java, you should be careful not to use interfaces casually in performance-critical code. Nested Interfaces: An interface can be declared a member of a class or another interface. Such an interface is called a member interface or a nested interface. A nested interface can be declared as public, private, or protected. This differs from a top-level interface, which must either be declared as public or use the default access level. // This class contains a member interface. class A { // this is a nested interface public interface NestedIF { boolean isNotNegative(int x); } } // B implements the nested interface. class B implements A.NestedIF { public boolean isNotNegative(int x) { return x < 0 ? false: true; } } class NestedIFDemo { public static void main(String args[]) { // use a nested interface reference A.NestedIF nif = new B(); if(nif.isNotNegative(10)) System.out.println("10 is not negative"); if(nif.isNotNegative(-12)) System.out.println("this won't be displayed"); } } Interfaces Can Be Extended: One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. Any class that implements an interface must implement all methods required by that interface, including any that are inherited from other interfaces. Default Interface Methods (aka extension method) : A primary motivation for the default method was to provide a means by which interfaces could be expanded without breaking existing code. i.e. suppose you add another method without body in an interface. Then you will have to provide the body of that method in all the classes that implement that interface. Ex: default String getString() { return "Default String"; } For example, you might have a class that implements two interfaces. If each of these interfaces provides default methods, then some behavior is inherited from both. # In all cases, a class implementation takes priority over an interface default implementation. # In cases in which a class implements two interfaces that both have the same default method, but the class does not override that method, then an error will result. # In cases in which one interface inherits another, with both defining a common default method, the inheriting interface’s version of the method takes precedence. NOTE: static interface methods are not inherited by either an implementing class or a subinterface. i.e. static interface methods should have a body! They cannot be abstract. NOTE : when overriding methods, the access modifier should be same or better i.e. if in Parent Class it was protected, then then overridden should be either protected or public. ================================================ FILE: lectures/17-oop/notes/notes.txt ================================================ An enumeration is a list of named constants. In Java, an enumeration defines a class type. By making enumerations into classes, the capabilities of the enumeration are greatly expanded. An enumeration is created using the enum keyword. Enum declaration can be done outside a Class or inside a Class but not inside a Method We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt. /* internally above enum Color is converted to (Check Example.java) class Color { public static final Color Red = new Color(); public static final Color Blue = new Color(); public static final Color Green = new Color(); }*/ Enum and Inheritance : -All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else. -An enum cannot be a superclass. -toString() method is overridden in java.lang.Enum class, which returns enum constant name. -enum can implement many interfaces. Two enumeration constants can be compared for equality by using the == relational operator. values(), ordinal() and valueOf() methods : These methods are present inside java.lang.Enum. -values() method can be used to return all values present inside enum. -Order is important in enums.By using ordinal() method, each enum constant index can be found, just like array index. -valueOf() method returns the enum constant of the specified string value, if exists. enum and constructor : -enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading. -We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly. -And the constructor cannot be the public or protected it must have private or default modifiers. -Why? if we create public or protected, it will allow initializing more than one objects. -This is totally against enum concept. enum and methods : enum can contain concrete methods only i.e. no any abstract method. You can compare for equality an enumeration constant with any other object by using equals( ), which overrides the equals( ) method defined by Object. Although equals( ) can compare an enumeration constant to any other object, those two objects will be equal only if they both refer to the same constant,within the same enumeration. Simply having ordinal values in common will not cause equals( ) to return true if the two constants are from different enumerations. Remember, you can compare two enumeration references for equality by using ==. ================================================ FILE: lectures/17-oop/notes/overloading.txt ================================================ Overloading Methods: In Java, it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. In some cases, Java’s automatic type conversions can play a role in overload resolution. class OverloadDemo { void test(double a){ System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } } As you can see, this version of OverloadDemo does not define test(int). Therefore, when test( ) is called with an integer argument inside Overload, no matching method is found. However, Java can automatically convert an integer into a double, and this conversion can be used to resolve the call. Therefore, after test(int) is not found, Java elevates i to double and then calls test(double). Of course, if test(int) had been defined, it would have been called instead. Java will employ its automatic type conversions only if no exact match is found. Returning Objects: // Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); } } Output: ob1.a: 2 ob2.a: 12 As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it is returned to the calling routine. Since all objects are dynamically allocated using new, you don’t need to worry about an object going out-of-scope because the method in which it was created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place. ================================================ FILE: lectures/17-oop/notes/overriding.txt ================================================ In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within its subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. (Check display functions in box classes) Dynamic Method Dispatch: Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Let’s begin by restating an important principle: a superclass reference variable can refer to a subclass object. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. If B extends A then you can override a method in A through B with changing the return type of method to B. ================================================ FILE: lectures/17-oop/notes/packages.txt ================================================ Packages are containers for classes. They are used to keep the class name space compartmentalized. For example, a package allows you to create a class named List, which you can store in your own package without concern that it will collide with some other class named List stored elsewhere. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions. The package is both a naming and a visibility control mechanism. The following statement creates a package called MyPackage: package MyPackage; Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. A package hierarchy must be reflected in the file system of your Java development system. For example, a package declared as package java.awt.image; needs to be stored in java\awt\image in a Windows environment. Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored. How does the Java run-time system know where to look for packages that you create? The answer has three parts. - First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in a subdirectory of the current directory, it will be found. - Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. - Third, you can use the -classpath option with java and javac to specify the path to your classes. When a package is imported, only those items within the package declared as public will be available to non-subclasses in the importing code. ================================================ FILE: lectures/17-oop/notes/static.txt ================================================ Understanding static: When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It cannot access non-static data (instance variables) A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference. In fact, you can access a non-static member in a static context by specifying the object reference explicitly : public class Human { String message = "Hello World"; public static void display(Human human){ System.out.println(human.message); } public static void main(String[] args) { Human kunal = new Human(); kunal.message = "Kunal's message"; Human.display(kunal); } } A static method can call only other static methods and cannot call a non-static method from it. A static method can be accessed directly by the class name and doesn’t need any object A static method cannot refer to "this" or "super" keywords in anyway If you need to do computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded. // Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a*4 or 12. Then main( ) is called, which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x. Here is the output of the program: Static block initialized. x = 42 a = 3 b = 12 Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place. NOTE: Only nested classes can be static. NOTE: Static inner classes can have static variables You cant override the inherited static methods, as in java overriding takes place by resolving the type of object at run-time and not compile time, and then calling the respective method. Static methods are class level methods, so it is always resolved during compile time. Static INTERFACE METHODS are not inherited by either an implementing class or a sub-interface. NOTE: public class Static { // class Test // ERROR static class Test{ String name; public Test(String name) { this.name = name; } } public static void main(String[] args) { Test a = new Test("Kunal"); Test b = new Test("Rahul"); System.out.println(a.name); // Kunal System.out.println(b.name); // Rahul } } Because : The static keyword may modify the declaration of a member type C within the body of a non-inner class or interface T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances. Here, test does not have any instance of it's outer class Static. Neither does main. But main & Test can have instances of each other. ================================================ FILE: lectures/18-linkedlist/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/18-linkedlist/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/18-linkedlist/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/18-linkedlist/code/code.iml ================================================ ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/CLL.java ================================================ package com.kunal; public class CLL { private Node head; private Node tail; public CLL() { this.head = null; this.tail = null; } public void insert(int val) { Node node = new Node(val); if (head == null) { head = node; tail = node; return; } tail.next = node; node.next = head; tail = node; } public void display() { Node node = head; if (head != null) { do { System.out.print(node.val + " -> "); if (node.next != null) { node = node.next; } } while (node != head); } System.out.println("HEAD"); } public void delete(int val) { Node node = head; if (node == null) { return; } if (head == tail){ head = null; tail = null; return; } if (node.val == val) { head = head.next; tail.next = head; return; } do { Node n = node.next; if (n.val == val) { node.next = n.next; break; } node = node.next; } while (node != head); } private class Node { int val; Node next; public Node(int val) { this.val = val; } } } ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/DLL.java ================================================ package com.kunal; public class DLL { private Node head; public void insertFirst(int val) { Node node = new Node(val); node.next = head; node.prev = null; if (head != null) { head.prev = node; } head = node; } public void display() { Node node = head; Node last = null; while (node != null) { System.out.print(node.val + " -> "); last = node; node = node.next; } System.out.println("END"); System.out.println("Print in reverse"); while (last != null) { System.out.print(last.val + " -> "); last = last.prev; } System.out.println("START"); } public void insertLast(int val) { Node node = new Node(val); Node last = head; node.next = null; if (head == null) { node.prev = null; head = node; return; } while (last.next != null) { last = last.next; } last.next = node; node.prev = last; } public Node find(int value) { Node node = head; while (node != null) { if (node.val == value) { return node; } node = node.next; } return null; } public void insert(int after, int val) { Node p = find(after); if (p == null) { System.out.println("does not exist"); return; } Node node = new Node(val); node.next = p.next; p.next = node; node.prev = p; if (node.next != null) { node.next.prev = node; } } private class Node { int val; Node next; Node prev; public Node(int val) { this.val = val; } public Node(int val, Node next, Node prev) { this.val = val; this.next = next; this.prev = prev; } } } ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/InterviewQuestions.java ================================================ package com.kunal; import javax.swing.*; public class InterviewQuestions { // https://leetcode.com/problems/linked-list-cycle // Amazon and Microsoft public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { return true; } } return false; } // find length of the cycle public int lengthCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { // calculate the length ListNode temp = slow; int length = 0; do { temp = temp.next; length++; } while (temp != slow); return length; } } return 0; } // https://leetcode.com/problems/linked-list-cycle-ii/ public ListNode detectCycle(ListNode head) { int length = 0; ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { length = lengthCycle(slow); break; } } if (length == 0) { return null; } // find the start node ListNode f = head; ListNode s = head; while (length > 0) { s = s.next; length--; } // keep moving both forward and they will meet at cycle start while (f != s) { f = f.next; s = s.next; } return s; } // Google: https://leetcode.com/problems/happy-number/ public boolean isHappy(int n) { int slow = n; int fast = n; do { slow = findSquare(slow); fast = findSquare(findSquare(fast)); } while (slow != fast); if (slow == 1) { return true; } return false; } private int findSquare(int number) { int ans = 0; while (number > 0) { int rem = number % 10 ; ans += rem * rem; number /= 10; } return ans; } // https://leetcode.com/problems/middle-of-the-linked-list/submissions/ public ListNode middleNode(ListNode head) { ListNode s = head; ListNode f = head; while (f != null && f.next != null) { s = s.next; f = f.next.next; } return s; } // https://leetcode.com/problems/reverse-linked-list/submissions/ // google, apple, amazon, microsoft public ListNode reverseList(ListNode head) { if (head == null) { return head; } ListNode prev = null; ListNode present = head; ListNode next = present.next; while (present != null) { present.next = prev; prev = present; present = next; if (next != null) { next = next.next; } } return prev; } // Google, Microsoft, Facebook: https://leetcode.com/problems/reverse-linked-list-ii/ public ListNode reverseBetween(ListNode head, int left, int right) { if (left == right) { return head; } // skip the first left-1 nodes ListNode current = head; ListNode prev = null; for (int i = 0; current != null && i < left - 1; i++) { prev = current; current = current.next; } ListNode last = prev; ListNode newEnd = current; // reverse between left and right ListNode next = current.next; for (int i = 0; current != null && i < right - left + 1; i++) { current.next = prev; prev = current; current = next; if (next != null) { next = next.next; } } if (last != null) { last.next = prev; } else { head = prev; } newEnd.next = current; return head; } // google, amazon, facebook, microsoft: https://leetcode.com/problems/reverse-nodes-in-k-group/ public ListNode reverseKGroup(ListNode head, int k) { if (k <= 1 || head == null) { return head; } ListNode current = head; ListNode prev = null; int length = getLength(head); int count = length / k; while (count > 0) { ListNode last = prev; ListNode newEnd = current; ListNode next = current.next; for (int i = 0; current != null && i < k; i++) { current.next = prev; prev = current; current = next; if (next != null) { next = next.next; } } if (last != null) { last.next = prev; } else { head = prev; } newEnd.next = current; prev = newEnd; count--; } return head; } public int getLength(ListNode head) { ListNode node = head; int length = 0; while (node != null) { length++; node = node.next; } return length; } // https://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/ public ListNode reverseAlternateKGroup(ListNode head, int k) { if (k <= 1 || head == null) { return head; } // skip the first left-1 nodes ListNode current = head; ListNode prev = null; while (current != null) { ListNode last = prev; ListNode newEnd = current; // reverse between left and right ListNode next = current.next; for (int i = 0; current != null && i < k; i++) { current.next = prev; prev = current; current = next; if (next != null) { next = next.next; } } if (last != null) { last.next = prev; } else { head = prev; } newEnd.next = current; // skip the k nodes for (int i = 0; current != null && i < k; i++) { prev = current; current = current.next; } } return head; } // linkedin, google, facebook, microsoft, amazon, apple // https://leetcode.com/problems/palindrome-linked-list/ public boolean isPalindrome(ListNode head) { ListNode mid = middleNode(head); ListNode headSecond = reverseList(mid); ListNode rereverseHead = headSecond; // compare both the halves while (head != null && headSecond != null) { if (head.val != headSecond.val) { break; } head = head.next; headSecond = headSecond.next; } reverseList(rereverseHead); return head == null || headSecond == null; } // https://leetcode.com/problems/reorder-list/ // Google, Facebook public void reorderList(ListNode head) { if (head == null || head.next == null) { return; } ListNode mid = middleNode(head); ListNode hs = reverseList(mid); ListNode hf = head; // rearrange while (hf != null && hs != null) { ListNode temp = hf.next; hf.next = hs; hf = temp; temp = hs.next; hs.next = hf; hs = temp; } // next of tail to null if (hf != null) { hf.next = null; } } // FaceBook, Twitter, Google: https://leetcode.com/problems/rotate-list/ public ListNode rotateRight(ListNode head, int k) { if (k <= 0 || head == null || head.next == null) { return head; } ListNode last = head; int length = 1; while (last.next != null) { last = last.next; length++; } last.next = head; int rotations = k % length; int skip = length - rotations; ListNode newLast = head; for (int i = 0; i < skip - 1; i++) { newLast = newLast.next; } head = newLast.next; newLast.next = null; return head; } } class ListNode { int val; ListNode next; public ListNode() { } ListNode(int x) { val = x; next = null; } } ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/LL.java ================================================ package com.kunal; public class LL { private Node head; private Node tail; private int size; public LL() { this.size = 0; } public void insertFirst(int val) { Node node = new Node(val); node.next = head; head = node; if (tail == null) { tail = head; } size += 1; } public void insertLast(int val) { if (tail == null) { insertFirst(val); return; } Node node = new Node(val); tail.next = node; tail = node; size++; } public void insert(int val, int index) { if (index == 0) { insertFirst(val); return; } if (index == size) { insertLast(val); return; } Node temp = head; for (int i = 1; i < index; i++) { temp = temp.next; } Node node = new Node(val, temp.next); temp.next = node; size++; } // insert using recursion public void insertRec(int val, int index) { head = insertRec(val, index, head); } private Node insertRec(int val, int index, Node node) { if (index == 0) { Node temp = new Node(val, node); size++; return temp; } node.next = insertRec(val, index-1, node.next); return node; } public int deleteLast() { if (size <= 1) { return deleteFirst(); } Node secondLast = get(size - 2); int val = tail.value; tail = secondLast; tail.next = null; size--; return val; } public int delete(int index) { if (index == 0) { return deleteFirst(); } if (index == size - 1) { return deleteLast(); } Node prev = get(index - 1); int val = prev.next.value; prev.next = prev.next.next; size--; return val; } public Node find(int value) { Node node = head; while (node != null) { if (node.value == value) { return node; } node = node.next; } return null; } public Node get(int index) { Node node = head; for (int i = 0; i < index; i++) { node = node.next; } return node; } public int deleteFirst() { int val = head.value; head = head.next; if (head == null) { tail = null; } size--; return val; } public void display() { Node temp = head; while (temp != null) { System.out.print(temp.value + " -> "); temp = temp.next; } System.out.println("END"); } private class Node { private int value; private Node next; public Node(int value) { this.value = value; } public Node(int value, Node next) { this.value = value; this.next = next; } } // https://leetcode.com/problems/remove-duplicates-from-sorted-list public void duplicates() { Node node = head; while (node.next != null) { if (node.value == node.next.value) { node.next = node.next.next; size--; } else { node = node.next; } } tail = node; tail.next = null; } // https://leetcode.com/problems/merge-two-sorted-lists/submissions/ public static LL merge(LL first, LL second) { Node f = first.head; Node s = second.head; LL ans = new LL(); while (f != null && s != null) { if (f.value < s.value) { ans.insertLast(f.value); f = f.next; } else { ans.insertLast(s.value); s = s.next; } } while (f != null) { ans.insertLast(f.value); f = f.next; } while (s != null) { ans.insertLast(s.value); s = s.next; } return ans; } public void bubbleSort() { bubbleSort(size - 1, 0); } private void bubbleSort(int row, int col) { if (row == 0) { return; } if (col < row) { Node first = get(col); Node second = get(col + 1); if (first.value > second.value) { // swap if (first == head) { head = second; first.next = second.next; second.next = first; } else if (second == tail) { Node prev = get(col - 1); prev.next = second; tail = first; first.next = null; second.next = tail; } else { Node prev = get(col - 1); prev.next = second; first.next = second.next; second.next = first; } } bubbleSort(row, col + 1); } else { bubbleSort(row - 1, 0); } } // recursion reverse private void reverse(Node node) { if (node == tail) { head = tail; return; } reverse(node.next); tail.next = node; tail = node; tail.next = null; } // in place reversal of linked list // google, microsoft, apple, amazon: https://leetcode.com/problems/reverse-linked-list/ public void reverse() { if (size < 2) { return; } Node prev = null; Node present = head; Node next = present.next; while (present != null) { present.next = prev; prev = present; present = next; if (next != null) { next = next.next; } } head = prev; } public static void main(String[] args) { LL first = new LL(); LL second = new LL(); first.insertLast(1); first.insertLast(3); first.insertLast(5); second.insertLast(1); second.insertLast(2); second.insertLast(9); second.insertLast(14); LL ans = LL.merge(first, second); ans.display(); LL list = new LL(); for (int i = 7; i > 0; i--) { list.insertLast(i); } list.display(); list.bubbleSort(); list.display(); } } ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/Main.java ================================================ package com.kunal; public class Main { public static void main(String[] args) { LL list = new LL(); list.insertFirst(3); list.insertFirst(2); list.insertFirst(8); list.insertFirst(17); list.insertLast(99); list.insert(100, 3); list.display(); System.out.println(list.deleteFirst()); list.display(); System.out.println(list.deleteLast()); list.display(); System.out.println(list.delete(2)); list.display(); list.insertRec(88, 2); list.display(); // DLL list = new DLL(); // list.insertFirst(3); // list.insertFirst(2); // list.insertFirst(8); // list.insertFirst(17); // list.insertLast(99); // list.insert(8, 65); // // list.display(); // CLL list = new CLL(); // list.insert(23); // list.insert(3); // list.insert(19); // list.insert(75); // list.display(); // list.delete(19); // list.display(); } } ================================================ FILE: lectures/18-linkedlist/code/src/com/kunal/MergeSort.java ================================================ package com.kunal; public class MergeSort { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode mid = getMid(head); ListNode left = sortList(head); ListNode right = sortList(mid); return merge(left, right); } ListNode merge(ListNode list1, ListNode list2) { ListNode dummyHead = new ListNode(); ListNode tail = dummyHead; while (list1 != null && list2 != null) { if (list1.val < list2.val) { tail.next = list1; list1 = list1.next; tail = tail.next; } else { tail.next = list2; list2 = list2.next; tail = tail.next; } } tail.next = (list1 != null) ? list1 : list2; return dummyHead.next; } ListNode getMid(ListNode head) { ListNode midPrev = null; while (head != null && head.next != null) { midPrev = (midPrev == null) ? head : midPrev.next; head = head.next.next; } ListNode mid = midPrev.next; midPrev.next = null; return mid; } } ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/.gitignore ================================================ # Default ignored files /shelf/ /workspace.xml ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/description.html ================================================ Simple Java application that includes a class with main() method ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/encodings.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/misc.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/modules.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/project-template.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/uiDesigner.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/.idea/vcs.xml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/code.iml ================================================ ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/CircularQueue.java ================================================ package com.kunal; public class CircularQueue { protected int[] data; private static final int DEFAULT_SIZE = 10; protected int end = 0; protected int front = 0; private int size = 0; public CircularQueue(){ this(DEFAULT_SIZE); } public CircularQueue(int size) { this.data = new int[size]; } public boolean isFull() { return size == data.length; // ptr is at last index } public boolean isEmpty() { return size == 0; } public boolean insert(int item) { if (isFull()) { return false; } data[end++] = item; end = end % data.length; size++; return true; } public int remove() throws Exception { if (isEmpty()) { throw new Exception("Queue is empty"); } int removed = data[front++]; front = front % data.length; size--; return removed; } public int front() throws Exception{ if (isEmpty()) { throw new Exception("Queue is empty"); } return data[front]; } public void display() { if (isEmpty()) { System.out.println("Empty"); return; } int i = front; do { System.out.print(data[i] + " -> "); i++; i %= data.length; } while (i != end); System.out.println("END"); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/CustomQueue.java ================================================ package com.kunal; public class CustomQueue { private int[] data; private static final int DEFAULT_SIZE = 10; int end = 0; public CustomQueue(){ this(DEFAULT_SIZE); } public CustomQueue(int size) { this.data = new int[size]; } public boolean isFull() { return end == data.length; // ptr is at last index } public boolean isEmpty() { return end == 0; } public boolean insert(int item) { if (isFull()) { return false; } data[end++] = item; return true; } public int remove() throws Exception { if (isEmpty()) { throw new Exception("Queue is empty"); } int removed = data[0]; // shift the elements to left for (int i = 1; i < end; i++) { data[i-1] = data[i]; } end--; return removed; } public int front() throws Exception{ if (isEmpty()) { throw new Exception("Queue is empty"); } return data[0]; } public void display() { for (int i = 0; i < end; i++) { System.out.print(data[i] + " <- "); } System.out.println("END"); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/CustomStack.java ================================================ package com.kunal; public class CustomStack { protected int[] data; private static final int DEFAULT_SIZE = 10; int ptr = -1; public CustomStack(){ this(DEFAULT_SIZE); } public CustomStack(int size) { this.data = new int[size]; } public boolean push(int item) { if (isFull()) { System.out.println("Stack is full!!"); return false; } ptr++; data[ptr] = item; return true; } public int pop() throws StackException { if (isEmpty()) { throw new StackException("Cannot pop from an empty stack!!"); } // int removed = data[ptr]; // ptr--; // return removed; return data[ptr--]; } public int peek() throws StackException { if (isEmpty()) { throw new StackException("Cannot peek from an empty stack!!"); } return data[ptr]; } public boolean isFull() { return ptr == data.length - 1; // ptr is at last index } public boolean isEmpty() { return ptr == -1; } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/DynamicQueue.java ================================================ package com.kunal; public class DynamicQueue extends CircularQueue{ public DynamicQueue() { super(); } public DynamicQueue(int size) { super(size); } @Override public boolean insert(int item) { // this takes care of it being full if (this.isFull()) { // double the array size int[] temp = new int[data.length * 2]; // copy all previous items in new data for (int i = 0; i < data.length; i++) { temp[i] = data[(front + i) % data.length]; } front = 0; end = data.length; data = temp; } // at this point we know that array is not full // insert item return super.insert(item); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/DynamicStack.java ================================================ package com.kunal; public class DynamicStack extends CustomStack{ public DynamicStack() { super(); // it will call CustomStack() } public DynamicStack(int size) { super(size); // it will call CustomStack(int size) } @Override public boolean push(int item) { // this takes care of it being full if (this.isFull()) { // double the array size int[] temp = new int[data.length * 2]; // copy all previous items in new data for (int i = 0; i < data.length; i++) { temp[i] = data[i]; } data = temp; } // at this point we know that array is not full // insert item return super.push(item); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/InBuiltExamples.java ================================================ package com.kunal; import java.util.*; public class InBuiltExamples { public static void main(String[] args) { Stack stack = new Stack<>(); stack.push(34); stack.push(45); stack.push(2); stack.push(9); stack.push(18); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); Queue queue = new LinkedList<>(); queue.add(3); queue.add(6); queue.add(5); queue.add(19); queue.add(1); System.out.println(queue.remove()); System.out.println(queue.remove()); Deque deque = new ArrayDeque<>(); deque.add(89); deque.addLast(78); deque.removeFirst(); // etc etc } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/QueueMain.java ================================================ package com.kunal; public class QueueMain { public static void main(String[] args) throws Exception { CircularQueue queue = new CircularQueue(5); queue.insert(3); queue.insert(6); queue.insert(5); queue.insert(19); queue.insert(1); queue.display(); System.out.println(queue.remove()); queue.insert(133); queue.display(); System.out.println(queue.remove()); queue.insert(99); queue.display(); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/StackException.java ================================================ package com.kunal; public class StackException extends Exception{ public StackException(String message) { super(message); } } ================================================ FILE: lectures/19-stacks-n-queues/code/src/com/kunal/StackMain.java ================================================ package com.kunal; public class StackMain { public static void main(String[] args) throws StackException { CustomStack stack = new DynamicStack(5); stack.push(34); stack.push(45); stack.push(2); stack.push(9); stack.push(18); stack.push(89); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } } ================================================ FILE: lectures/19-stacks-n-queues/questions/LargestAreaHistogram.java ================================================ import java.util.Stack; class Main { public static void main(String[] args) { } public int largestRectangleArea(int[] heights) { Stack stack = new Stack<>(); int max = 0; stack.push(0); for (int i = 1; i < heights.length; i++) { while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) { max = getMax(heights, stack, max, i); } stack.push(i); } int i = heights.length; while (!stack.isEmpty()) { max = getMax(heights, stack, max, i); } return max; } private static int getMax(int[] arr, Stack stack, int max, int i) { int area; int popped = stack.pop(); if (stack.isEmpty()) { area = arr[popped] * i; } else { area = arr[popped] * (i - 1 - stack.peek()); } return Math.max(max, area); } } ================================================ FILE: lectures/19-stacks-n-queues/questions/QueueUsingStack.java ================================================ import java.util.Stack; public class QueueUsingStack { private Stack first; private Stack second; public QueueUsingStack() { first = new Stack<>(); second = new Stack<>(); } public void add(int item) { first.push(item); } public int remove() throws Exception { while (!first.isEmpty()) { second.push(first.pop()); } int removed = second.pop(); while (!second.isEmpty()) { first.push(second.pop()); } return removed; } public int peek() throws Exception { while (!first.isEmpty()) { second.push(first.pop()); } int peeked = second.peek(); while (!second.isEmpty()) { first.push(second.pop()); } return peeked; } public boolean isEmpty() { return first.isEmpty(); } } ================================================ FILE: lectures/19-stacks-n-queues/questions/QueueUsingStackRemove.java ================================================ import java.util.Stack; public class QueueUsingStackRemove { private Stack first; private Stack second; public QueueUsingStackRemove() { first = new Stack<>(); second = new Stack<>(); } public void add(int item) throws Exception { while (!first.isEmpty()) { second.push(first.pop()); } first.push(item); while (!second.isEmpty()) { first.push(second.pop()); } } public int remove() throws Exception { return first.pop(); } public int peek() throws Exception { return first.peek(); } public boolean isEmpty() { return first.isEmpty(); } } ================================================ FILE: lectures/19-stacks-n-queues/questions/TwoStacks.java ================================================ import java.util.*; class TwoStacks { static int twoStacks(int x, int[] a, int[] b) { return twoStacks(x, a, b, 0, 0) - 1; } private static int twoStacks(int x, int[] a, int[] b, int sum, int count) { if (sum > x) { return count; } if (a.length == 0 || b.length == 0) { return count; } int ans1 = twoStacks(x, Arrays.copyOfRange(a, 1, a.length), b, sum + a[0], count + 1); int ans2 = twoStacks(x, a, Arrays.copyOfRange(b, 1, b.length), sum + a[0], count + 1); return Math.max(ans1, ans2); } public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); for (int i = 0; i < t; i++) { int n = s.nextInt(); int m = s.nextInt(); int x = s.nextInt(); int[] a = new int[n]; int[] b = new int[m]; for (int j = 0; j < n; j++) { a[j] = s.nextInt(); } for (int j = 0; j < m; j++) { b[j] = s.nextInt(); } System.out.println(twoStacks(x, a, b)); } } } ================================================ FILE: lectures/19-stacks-n-queues/questions/ValidParenMinAdd.java ================================================ import java.util.Stack; class Solution { public int minAddToMakeValid(String s) { Stack stack = new Stack<>(); for (char ch : s.toCharArray()) { if (ch == ')') { if (!stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else { stack.push(ch); } } else { stack.push(ch); } } return stack.size(); } } ================================================ FILE: lectures/19-stacks-n-queues/questions/ValidParenthesis.java ================================================ import java.util.Stack; class Solution { public boolean isValid(String s) { Stack stack = new Stack<>(); for (char ch : s.toCharArray()) { if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } else { if (ch == ')') { if (stack.isEmpty() || stack.pop() != '(') { return false; } } if (ch == '}') { if (stack.isEmpty() || stack.pop() != '{') { return false; } } if (ch == ']') { if (stack.isEmpty() || stack.pop() != '[') { return false; } } } } return stack.isEmpty(); } } ================================================ FILE: lectures/20-trees/code/AVL/.breakpoints ================================================ { "files": {} } ================================================ FILE: lectures/20-trees/code/AVL/.cache/replit/__replit_disk_meta.json ================================================ {"nonce":6822585830757037893,"last_updated":{"seconds":1690198025,"nanos":992471000}} ================================================ FILE: lectures/20-trees/code/AVL/.cache/replit/modules.stamp ================================================ 2jmj7l5rSw0yVb_vlWAYkK_YBwk= ================================================ FILE: lectures/20-trees/code/AVL/.cache/replit/nix/env.json ================================================ {"entries":{"replit.nix":{"env":{"AR":"ar","AS":"as","CC":"gcc","CONFIG_SHELL":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","CXX":"g++","HOST_PATH":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0/bin:/nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","JAVA_HOME":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0","LD":"ld","LOCALE_ARCHIVE":"/usr/lib/locale/locale-archive","NIX_BINTOOLS":"/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39","NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_BUILD_CORES":"16","NIX_BUILD_TOP":"/tmp","NIX_CC":"/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0","NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_CFLAGS_COMPILE":" -frandom-seed=vzlvbz7had -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include","NIX_ENFORCE_NO_NATIVE":"1","NIX_HARDENING_ENABLE":"fortify stackprotector pic strictoverflow format relro bindnow","NIX_INDENT_MAKE":"1","NIX_LDFLAGS":"-rpath /nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell/lib64 -rpath /nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib","NIX_STORE":"/nix/store","NM":"nm","OBJCOPY":"objcopy","OBJDUMP":"objdump","PATH":"/nix/store/bap4d0lpcrhpwmpb8ayjcgkmvfj62lnq-bash-interactive-5.1-p16/bin:/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/bin:/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0/bin:/nix/store/1gf2flfqnpqbr1b4p4qz2f72y42bs56r-gcc-11.3.0/bin:/nix/store/57xv61c5zi8pphjbcwxxjlgc34p61ic9-glibc-2.35-163-bin/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39/bin:/nix/store/039g378vc3pc3dvi9dzdlrd0i4q93qwf-binutils-2.39/bin:/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0/bin:/nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","RANLIB":"ranlib","READELF":"readelf","SIZE":"size","SOURCE_DATE_EPOCH":"315532800","STRINGS":"strings","STRIP":"strip","XDG_DATA_DIRS":"/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/share","_":"/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin/env","__ETC_PROFILE_SOURCED":"1","buildInputs":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0 /nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6 /nix/store/m6gcpi1ii6rghy04cjwjddcavv7i90df-jdt-language-server-1.9.0 /nix/store/84xs5alhs01zrbr4ywm05kxbjbp5590l-java-debug","buildPhase":"echo \"------------------------------------------------------------\" \u003e\u003e$out\necho \" WARNING: the existence of this path is not guaranteed.\" \u003e\u003e$out\necho \" It is an internal implementation detail for pkgs.mkShell.\" \u003e\u003e$out\necho \"------------------------------------------------------------\" \u003e\u003e$out\necho \u003e\u003e $out\n# Record all build inputs as runtime dependencies\nexport \u003e\u003e $out\n","builder":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","cmakeFlags":"","configureFlags":"","depsBuildBuild":"","depsBuildBuildPropagated":"","depsBuildTarget":"","depsBuildTargetPropagated":"","depsHostHost":"","depsHostHostPropagated":"","depsTargetTarget":"","depsTargetTargetPropagated":"","doCheck":"","doInstallCheck":"","mesonFlags":"","name":"nix-shell","nativeBuildInputs":"","out":"/nix/store/vzlvbz7had654yd78xdypqh0sw6zr8x3-nix-shell","outputs":"out","patches":"","phases":"buildPhase","propagatedBuildInputs":"","propagatedNativeBuildInputs":"","shell":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","shellHook":"","stdenv":"/nix/store/kmfaajdpyyyg319vfqni5jm9wkxjmf73-stdenv-linux","strictDeps":"","system":"x86_64-linux"},"dependencies":[{"path":"replit.nix","mod_time":"2023-05-12T19:41:48.477539597Z"}],"channel":"stable-22_11","channel_nix_path":"/nix/store/1hxr7x3df6jw0h175dkd2qybvkdscsj1-nixpkgs-stable-22_11-22.11.tar.gz/nixpkgs-stable-22_11"}}} ================================================ FILE: lectures/20-trees/code/AVL/.classpath ================================================ ================================================ FILE: lectures/20-trees/code/AVL/.project ================================================ myartifactid org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature 1679078569810 30 org.eclipse.core.resources.regexFilterMatcher node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ ================================================ FILE: lectures/20-trees/code/AVL/.replit ================================================ compile = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" run = "java -classpath .:target/dependency/* Main" entrypoint = "Main.java" hidden = ["**/*.class"] [packager] language = "java" [packager.features] packageSearch = true [languages.java] pattern = "**/*.java" [languages.java.languageServer] start = "jdt-language-server" [unitTest] language = "java" [nix] channel = "stable-22_11" [debugger] support = true [debugger.compile] command = "javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -g -d . $(find . -type f -name '*.java')" [debugger.interactive] transport = "localhost:0" connectTimeout = 60 startCommand = "java-debug" [debugger.interactive.initializeMessage] command = "initialize" type = "request" [debugger.interactive.initializeMessage.arguments] adapterID = "cppdbg" clientID = "replit" clientName = "replit.com" columnsStartAt1 = true linesStartAt1 = true locale = "en-us" pathFormat = "path" supportsInvalidatedEvent = true supportsProgressReporting = true supportsRunInTerminalRequest = true supportsVariablePaging = true supportsVariableType = true [debugger.interactive.launchMessage] command = "launch" type = "request" [debugger.interactive.launchMessage.arguments] classPaths = ["."] mainClass = "Main" [deployment] build = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" run = "java -classpath .:target/dependency/* Main" ================================================ FILE: lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.apt.core.prefs ================================================ eclipse.preferences.version=1 org.eclipse.jdt.apt.aptEnabled=false ================================================ FILE: lectures/20-trees/code/AVL/.settings/org.eclipse.jdt.core.prefs ================================================ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.5 ================================================ FILE: lectures/20-trees/code/AVL/.settings/org.eclipse.m2e.core.prefs ================================================ activeProfiles= eclipse.preferences.version=1 resolveWorkspaceProjects=true version=1 ================================================ FILE: lectures/20-trees/code/AVL/.upm/store.json ================================================ {"version":2,"languages":{"java-maven":{"specfileHash":"3ff69d18804bae1a389cb7ea263f0c5b","lockfileHash":"3ff69d18804bae1a389cb7ea263f0c5b"}}} ================================================ FILE: lectures/20-trees/code/AVL/AVL.java ================================================ class AVL { public class Node { private int value; private Node left; private Node right; private int height; public Node(int value) { this.value = value; } public int getValue() { return value; } } private Node root; public AVL() { } public int height() { return height(root); } private int height(Node node) { if (node == null) { return -1; } return node.height; } public void insert(int value) { root = insert(value, root); } private Node insert(int value, Node node) { if (node == null) { node = new Node(value); return node; } if (value < node.value) { node.left = insert(value, node.left); } if (value > node.value) { node.right = insert(value, node.right); } node.height = Math.max(height(node.left), height(node.right)) + 1; return rotate(node); } private Node rotate(Node node) { if (height(node.left) - height(node.right) > 1) { // left heavy if(height(node.left.left) - height(node.left.right) > 0) { // left left case return rightRotate(node); } if(height(node.left.left) - height(node.left.right) < 0) { // left right case node.left = leftRotate(node.left); return rightRotate(node); } } if (height(node.left) - height(node.right) < -1) { // right heavy if(height(node.right.left) - height(node.right.right) < 0) { // right right case return leftRotate(node); } if(height(node.right.left) - height(node.right.right) > 0) { // left right case node.right = rightRotate(node.right); return leftRotate(node); } } return node; } public Node rightRotate(Node p) { Node c = p.left; Node t = c.right; c.right = p; p.left = t; p.height = Math.max(height(p.left), height(p.right) + 1); c.height = Math.max(height(c.left), height(c.right) + 1); return c; } public Node leftRotate(Node c) { Node p = c.right; Node t = p.left; p.left = c; c.right = t; p.height = Math.max(height(p.left), height(p.right) + 1); c.height = Math.max(height(c.left), height(c.right) + 1); return p; } public void populate(int[] nums) { for (int i = 0; i < nums.length; i++) { this.insert(nums[i]); } } public void populatedSorted(int[] nums) { populatedSorted(nums, 0, nums.length); } private void populatedSorted(int[] nums, int start, int end) { if (start >= end) { return; } int mid = (start + end) / 2; this.insert(nums[mid]); populatedSorted(nums, start, mid); populatedSorted(nums, mid + 1, end); } public void display() { display(this.root, "Root Node: "); } private void display(Node node, String details) { if (node == null) { return; } System.out.println(details + node.value); display(node.left, "Left child of " + node.value + " : "); display(node.right, "Right child of " + node.value + " : "); } public boolean isEmpty() { return root == null; } public boolean balanced() { return balanced(root); } private boolean balanced(Node node) { if (node == null) { return true; } return Math.abs(height(node.left) - height(node.right)) <= 1 && balanced(node.left) && balanced(node.right); } } ================================================ FILE: lectures/20-trees/code/AVL/Main.java ================================================ class Main { public static void main(String[] args) { AVL tree = new AVL(); for(int i=0; i < 1000; i++) { tree.insert(i); } System.out.println(tree.height()); } } ================================================ FILE: lectures/20-trees/code/Advance questions/DoubleLinkedList.java ================================================ public class DoubleLinkedList { LLNode head; LLNode tail; public TreeNode convert(TreeNode root) { if (root == null) { return null; } helper(root); return head; } private void helper(TreeNode node) { if(node == null) { return null; } helper(node.left); LLNode newNode = new LLNode(node.val); if(head == null) { head = newNode; tail = newNode; } else { tail.next = newNode; newNode.prev = tail; tail = newNode; } helper(node.right); } } class LLNode { int val; LLNode prev; LLNode next; public LLNode (int val) { this.val = val; } } class TreeNode { int val; TreeNode left; TreeNode right; public TreeNode (int val) { this.val = val; } } ================================================ FILE: lectures/20-trees/code/Advance questions/KthSmallest.java ================================================ class KthSmallest { public int kthSmallest(TreeNode root, int k) { PriorityQueue minHeap = new PriorityQueue<>(); helper(root, minHeap, k); // remove k elements int ans = 0; for(int i=0; i minHeap, int k) { if (node == null) { return; } helper(node.left, minHeap, k); minHeap.offer(node.val); helper(node.right, minHeap, k); } } ================================================ FILE: lectures/20-trees/code/Advance questions/KthSmallest2.java ================================================ class KthSmallest { private int k; private int ans; public int kthSmallest(TreeNode root, int k) { this.k = k; helper(root); return ans; } private void helper(TreeNode node) { if (node == null) { return; } helper(node.left); k--; if(k==0) { ans = node.val; return; } helper(node.right); } } ================================================ FILE: lectures/20-trees/code/Advance questions/Main.java ================================================ class Main { public static void main(String[] args) { } } ================================================ FILE: lectures/20-trees/code/Advance questions/PreIn.java ================================================ class PreIn { public TreeNode buildTree(int[] preOrder, int[] inOrder) { HashMap map = new HashMap<>(); for(int i=0; i < inOrder.length; i++) { map.put(inOrder[i], i); } int[] index = {0}; return helper(preOrder, inOrder, 0, preOrder.length-1, map, index); } public TreeNode helper(int[] preOrder, int[] inOrder, int left, int right, HashMap map, int[] index) { if (left > right) { return null; } int current = preOrder[index[0]]; index[0]++; TreeNode node = new TreeNode(current); if (left == right) { return node; } node.left = helper(preOrder, inOrder, left, index - 1, map, index); node.right = helper(preOrder, inOrder, index + 1, right, map, index); return node; } } ================================================ FILE: lectures/20-trees/code/Advance questions/TwoNodeSwap.java ================================================ import java.util.*; class Node { int val; Node left; Node right; public Node (int val) { this.val = val; } } public class TwoNodeSwap { Node first; Node second; Node prev; public void helper(Node root) { iot(root); // swap int temp = first.val; first.val = second.val; second.val = temp; } private void iot(Node node) { if(node == null) { return; } iot(node.left); if(prev != null && prev.val > node.val) { if(first == null) { first = prev; } second = node; } prev = node; iot(node.right); } public void printIOT(Node node) { if(node == null) { return; } printIOT(node.left); System.out.print(node.val + " "); printIOT(node.right); } } ================================================ FILE: lectures/20-trees/code/Advance questions/TwoSum.java ================================================ class TwoSum { public boolean findTarget(TreeNode root, int k) { HashSet set = new HashSet<>(); return helper(root, k, set); } private boolean helper(TreeNode node, int k, HashSet set) { if(node == null) { return false; } if(set.contains(k - node.val)) { return true; } set.add(node.val); return helper(node.left, k, set) || helper(node.right, k , set); } } ================================================ FILE: lectures/20-trees/code/Advance questions/VerticalTraversal.java ================================================ class VerticalTraversal { public List> verticalTraversal(TreeNode node) { List> ans = new ArrayList>(); if (node == null) { return ans; } int col = 0; Queue> queue = new ArrayDeque<>(); Map> map = new HashMap(); queue.offer(new AbstractMap.SimpleEntry<>(node, col)); int min = 0; int max = 0; while(!queue.isEmpty()) { Map.Entry removed = queue.poll(); node = removed.getKey(); col = removed.getValue(); if(node != null) { if(!map.containsKey(col)) { map.put(col, new ArrayList()); } map.get(col).add(node.val); min = Math.min(min, col); max = Math.max(max, col); queue.offer(new AbstractMap.SimpleEntry<>(node.left, col-1)); queue.offer(new AbstractMap.SimpleEntry<>(node.right, col+1)); } } for(int i=min; i <= max; i++) { ans.add(map.get(i)); } return ans; } } ================================================ FILE: lectures/20-trees/code/Advance questions/WordLadder.java ================================================ public class WordLadder { public static int ladderLength(String beginWord, String endWord, List wordList) { if (!wordList.contains(endWord)) return 0; Set visited = new HashSet<>(); Queue q = new LinkedList<>(); q.offer(beginWord); int length = 0; while (!q.isEmpty()) { int size = q.size(); length++; for (int i = 0; i < size; i++) { String current = q.poll(); for (int j = 0; j < current.length(); j++) { char[] temp = current.toCharArray(); for (char c = 'a'; c <= 'z'; c++) { temp[j] = c; String newWord = new String(temp); if (newWord.equals(endWord)) return length + 1; if (wordList.contains(newWord) && !visited.contains(newWord)) { q.offer(newWord); visited.add(newWord); } } } } } return 0; } } ================================================ FILE: lectures/20-trees/code/Questions/.breakpoints ================================================ { "files": {} } ================================================ FILE: lectures/20-trees/code/Questions/.cache/replit/__replit_disk_meta.json ================================================ {"nonce":230126823490474653,"last_updated":{"seconds":1693514001,"nanos":185075000}} ================================================ FILE: lectures/20-trees/code/Questions/.cache/replit/modules.stamp ================================================ 2jmj7l5rSw0yVb_vlWAYkK_YBwk= ================================================ FILE: lectures/20-trees/code/Questions/.cache/replit/nix/env.json ================================================ {"entries":{"replit.nix":{"env":{"AR":"ar","AS":"as","CC":"gcc","CONFIG_SHELL":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","CXX":"g++","HOST_PATH":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0/bin:/nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","JAVA_HOME":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0","LD":"ld","LOCALE_ARCHIVE":"/usr/lib/locale/locale-archive","NIX_BINTOOLS":"/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39","NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_BUILD_CORES":"16","NIX_BUILD_TOP":"/tmp","NIX_CC":"/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0","NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu":"1","NIX_CFLAGS_COMPILE":" -frandom-seed=jzy97cgd5n -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include -isystem /nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/include -isystem /nix/store/0y971q54v6jm9ss243xhl4y0gnlsm9c8-zlib-1.2.13-dev/include","NIX_ENFORCE_NO_NATIVE":"1","NIX_HARDENING_ENABLE":"fortify stackprotector pic strictoverflow format relro bindnow","NIX_INDENT_MAKE":"1","NIX_LDFLAGS":"-rpath /nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell/lib64 -rpath /nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib -L/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/lib -L/nix/store/026hln0aq1hyshaxsdvhg0kmcm6yf45r-zlib-1.2.13/lib -L/nix/store/2h0a1ma7bp2vprkmh6n4n2k1hcn1z0x8-graalvm17-ce-22.3.0-lib/lib","NIX_STORE":"/nix/store","NM":"nm","OBJCOPY":"objcopy","OBJDUMP":"objdump","PATH":"/nix/store/bap4d0lpcrhpwmpb8ayjcgkmvfj62lnq-bash-interactive-5.1-p16/bin:/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/bin:/nix/store/dq0xwmsk1g0i2ayg6pb7y87na2knzylh-gcc-wrapper-11.3.0/bin:/nix/store/1gf2flfqnpqbr1b4p4qz2f72y42bs56r-gcc-11.3.0/bin:/nix/store/57xv61c5zi8pphjbcwxxjlgc34p61ic9-glibc-2.35-163-bin/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/1d6ian3r8kdzspw8hacjhl3xkp40g1lj-binutils-wrapper-2.39/bin:/nix/store/039g378vc3pc3dvi9dzdlrd0i4q93qwf-binutils-2.39/bin:/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0/bin:/nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6/bin:/nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0/bin:/nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug/bin:/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin:/nix/store/mydc6f4k2z73xlcz7ilif3v2lcaiqvza-findutils-4.9.0/bin:/nix/store/j9p3g8472iijd50vhdprx0nmk2fqn5gv-diffutils-3.8/bin:/nix/store/89zs7rms6x00xfq4dq6m7mjnhkr8a6r4-gnused-4.8/bin:/nix/store/86bp03jkmsl6f92w0yzg4s59g5mhxwmy-gnugrep-3.7/bin:/nix/store/hwcdqw4jrjnd37wxqgsd47hd0j8bnj09-gawk-5.1.1/bin:/nix/store/cfbhw8r8ags41vwqaz47r583d0p4h4a1-gnutar-1.34/bin:/nix/store/p3m1ndl1lapwrlh698bnb5lvvxh67378-gzip-1.12/bin:/nix/store/a8mhcagrsly7c7mpjrpsnaahk4aax056-bzip2-1.0.8-bin/bin:/nix/store/mblgz65m3zv9x548a3d5m96fj2pbwr09-gnumake-4.3/bin:/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin:/nix/store/v7ljksji50mg3w61dykaa3n3y79n6nil-patch-2.7.6/bin:/nix/store/zlcnmqq14jz5x9439jf937mvayyl63da-xz-5.2.7-bin/bin:/nix/store/y6aj732zm9m87c82fpvf103a1xb22blp-file-5.43/bin","RANLIB":"ranlib","READELF":"readelf","SIZE":"size","SOURCE_DATE_EPOCH":"315532800","STRINGS":"strings","STRIP":"strip","XDG_DATA_DIRS":"/nix/store/pr5n59mb4jzmfx6kanwxly0l07p861fg-patchelf-0.15.0/share","_":"/nix/store/a7gvj343m05j2s32xcnwr35v31ynlypr-coreutils-9.1/bin/env","__ETC_PROFILE_SOURCED":"1","buildInputs":"/nix/store/gpxl5qgg8kicmcvivwmybwjlpf7wh20l-graalvm17-ce-22.3.0 /nix/store/6z9ag3ihc8mq2hzsw48lhbznvzny65nz-apache-maven-3.8.6 /nix/store/a7s9klvriqi68xz3qjc0qyfl5h86xc16-jdt-language-server-1.9.0 /nix/store/48ifl2w60a3zp7yskbpnvn8jp9jdsb7k-java-debug","buildPhase":"echo \"------------------------------------------------------------\" \u003e\u003e$out\necho \" WARNING: the existence of this path is not guaranteed.\" \u003e\u003e$out\necho \" It is an internal implementation detail for pkgs.mkShell.\" \u003e\u003e$out\necho \"------------------------------------------------------------\" \u003e\u003e$out\necho \u003e\u003e $out\n# Record all build inputs as runtime dependencies\nexport \u003e\u003e $out\n","builder":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","cmakeFlags":"","configureFlags":"","depsBuildBuild":"","depsBuildBuildPropagated":"","depsBuildTarget":"","depsBuildTargetPropagated":"","depsHostHost":"","depsHostHostPropagated":"","depsTargetTarget":"","depsTargetTargetPropagated":"","doCheck":"","doInstallCheck":"","mesonFlags":"","name":"nix-shell","nativeBuildInputs":"","out":"/nix/store/jzy97cgd5naxlaqsllsvchv882ihalp4-nix-shell","outputs":"out","patches":"","phases":"buildPhase","propagatedBuildInputs":"","propagatedNativeBuildInputs":"","shell":"/nix/store/dsd5gz46hdbdk2rfdimqddhq6m8m8fqs-bash-5.1-p16/bin/bash","shellHook":"","stdenv":"/nix/store/kmfaajdpyyyg319vfqni5jm9wkxjmf73-stdenv-linux","strictDeps":"","system":"x86_64-linux"},"dependencies":[{"path":"replit.nix","mod_time":"2023-05-12T19:41:48.477539597Z"}],"channel":"stable-22_11","channel_nix_path":"/nix/store/g2zwsf4i26pngib77ask4m00n9pj2a03-nixpkgs-stable-22_11-22.11.tar.gz/nixpkgs-stable-22_11"}}} ================================================ FILE: lectures/20-trees/code/Questions/.classpath ================================================ ================================================ FILE: lectures/20-trees/code/Questions/.project ================================================ myartifactid org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature 1679078569810 30 org.eclipse.core.resources.regexFilterMatcher node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ ================================================ FILE: lectures/20-trees/code/Questions/.replit ================================================ compile = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" run = "java -classpath .:target/dependency/* Main" entrypoint = "Main.java" hidden = ["**/*.class"] [packager] language = "java" [packager.features] packageSearch = true [languages.java] pattern = "**/*.java" [languages.java.languageServer] start = "jdt-language-server" [unitTest] language = "java" [nix] channel = "stable-22_11" [debugger] support = true [debugger.compile] command = "javac -classpath .:/run_dir/junit-4.12.jar:target/dependency/* -g -d . $(find . -type f -name '*.java')" [debugger.interactive] transport = "localhost:0" connectTimeout = 60 startCommand = "java-debug" [debugger.interactive.initializeMessage] command = "initialize" type = "request" [debugger.interactive.initializeMessage.arguments] adapterID = "cppdbg" clientID = "replit" clientName = "replit.com" columnsStartAt1 = true linesStartAt1 = true locale = "en-us" pathFormat = "path" supportsInvalidatedEvent = true supportsProgressReporting = true supportsRunInTerminalRequest = true supportsVariablePaging = true supportsVariableType = true [debugger.interactive.launchMessage] command = "launch" type = "request" [debugger.interactive.launchMessage.arguments] classPaths = ["."] mainClass = "Main" [deployment] build = "javac -classpath .:target/dependency/* -d . $(find . -type f -name '*.java')" run = "java -classpath .:target/dependency/* Main" ================================================ FILE: lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.apt.core.prefs ================================================ eclipse.preferences.version=1 org.eclipse.jdt.apt.aptEnabled=false ================================================ FILE: lectures/20-trees/code/Questions/.settings/org.eclipse.jdt.core.prefs ================================================ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.5 ================================================ FILE: lectures/20-trees/code/Questions/.settings/org.eclipse.m2e.core.prefs ================================================ activeProfiles= eclipse.preferences.version=1 resolveWorkspaceProjects=true version=1 ================================================ FILE: lectures/20-trees/code/Questions/.upm/store.json ================================================ {"version":2,"languages":{"java-maven":{"specfileHash":"3ff69d18804bae1a389cb7ea263f0c5b","lockfileHash":"3ff69d18804bae1a389cb7ea263f0c5b"}}} ================================================ FILE: lectures/20-trees/code/Questions/BFS.java ================================================ class BFS { public List> levelOrder(TreeNode root) { List> result = new ArrayList<>(); if (root == null) { return result; } Queue queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); List currentLevel = new ArrayList<>(levelSize); for (int i=0; i < levelSize; i++) { TreeNode currentNode = queue.poll(); currentLevel.add(currentNode.val); if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } result.add(currentLevel); } return result; } public List rightSideView(TreeNode root) { List result = new ArrayList<>(); if (root == null) { return result; } Queue queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); for (int i=0; i < levelSize; i++) { TreeNode currentNode = queue.poll(); if (i == levelSize - 1) { result.add(currentNode.val); } if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } } return result; } public List averageOfLevels(TreeNode root) { List result = new ArrayList<>(); if (root == null) { return result; } Queue queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); double averageLevel = 0; for (int i=0; i < levelSize; i++) { TreeNode currentNode = queue.poll(); averageLevel += currentNode.val; if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } averageLevel = averageLevel / levelSize; result.add(averageLevel); } return result; } public TreeNode findSuccessor(TreeNode root, int key){ if (root == null) { return null; } Queue queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int levelSize = queue.size(); TreeNode currentNode = queue.poll(); if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } if (currentNode.val = key) { break; } } return queue.peek(); } public List> zigzagLevelOrder(TreeNode root) { List> result = new ArrayList<>(); if (root == null) { return result; } Deque queue = new LinkedList<>(); queue.add(root); boolean reverse = false; while (!queue.isEmpty()) { int levelSize = queue.size(); List currentLevel = new ArrayList<>(levelSize); for (int i=0; i < levelSize; i++) { if (!reverse) { TreeNode currentNode = queue.pollFirst(); currentLevel.add(currentNode.val); if (currentNode.left != null) { queue.addLast(currentNode.left); } if (currentNode.right != null) { queue.addLast(currentNode.right); } } else { TreeNode currentNode = queue.pollLast(); currentLevel.add(currentNode.val); if (currentNode.right != null) { queue.addFirst(currentNode.right); } if (currentNode.left != null) { queue.addFirst(currentNode.left); } } } reverse = !reverse; result.add(currentLevel); } return result; } public Node connect(Node root) { if (root == null){ return null; } Node leftMost = root; while (leftMost.left != null) { Node current = leftMost; while(current != null) { current.left.next = current.right; if(current.next != null) { current.right.next = current.next.left; } current = current.next; } leftMost = leftMost.left; } return root; } public boolean isCousins(TreeNode root, int x, int y) { TreeNode xx = findNode(root, x); TreeNode yy = findNode(root, y); return ( (level(root, xx, 0) == level(root, yy, 0)) && (!isSibling(root, xx, yy)) ); } TreeNode findNode(TreeNode node, int x) { if (node == null) { return null; } if (node.val == x) { return node; } TreeNode n = findNode(node.left, x); if (n != null) { return n; } return findNode(node.right, x); } boolean isSibling (TreeNode node, TreeNode x, TreeNode y) { if (node == null) { return false; } return ( (node.left == x && node.right == y) || (node.left == y && node.right == x) || isSibling(node.left, x, y) || isSibling(node.right, x, y) ); } int level (TreeNode node, TreeNode x, int lev) { if(node == null) { return 0; } if(node == x) { return lev; } int l = level(node.left, x, lev+1); if (l != 0) { return l; } return level(node.right, x, lev+1); } public boolean isSymmetric(TreeNode root) { Queue queue = new LinkedList<>(); queue.add(root.left); queue.add(root.right); while(!queue.isEmpty()) { TreeNode left = queue.poll(); TreeNode right = queue.poll(); if(left == null && right == null) { continue; } if(left == null || right == null) { return false;; } if (left.val != right.val) { return false; } queue.add(left.left); queue.add(right.right); queue.add(left.right); queue.add(right.left); } return true; } } ================================================ FILE: lectures/20-trees/code/Questions/DFS.java ================================================ class DFS { // dfs using stack void dfsStack(Node node) { if(node == null) { return; } Stack stack = new Stack<>(); stack.push(node); while(!stack.isEmpty()) { Node removed = stack.pop(); System.out.print(removed.val + " "); if(removed.right != null) { stack.push(removed.right); } if(removed.left != null) { stack.push(removed.left); } } } int diameter = 0; public int diameterOfBinaryTree(TreeNode root) { height(root); return diameter-1; } int height(TreeNode node) { if(node == null) { return 0; } int leftHeight = height(node.left); int rightHeight = height(node.right); int dia = leftHeight + rightHeight + 1; diameter = Math.max(diameter, dia); return Math.max(leftHeight, rightHeight) + 1; } public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode left = invertTree(root.left); TreeNode right = invertTree(root.right); root.left = right; root.right = left; return root; } public void flatten(TreeNode root) { TreeNode current = root; while (current != null) { if (current.left != null) { TreeNode temp = current.left; while(temp.right != null) { temp = temp.right; } temp.right = current.right; current.right = current.left; current.left= null; } current = current.right; } } public boolean isValidBST(TreeNode root) { return helper(root, null, null); } public boolean helper(TreeNode node, Integer low, Integer high) { if (node == null) { return true; } if (low != null && node.val <= low) { return false; } if(high != null && node.val >= high) { return false; } boolean leftTree = helper(node.left, low, node.val); boolean rightTree = helper(node.right, node.val, high); return leftTree && rightTree; } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } if (root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) { return root; } return left == null ? right : left; } int count = 0; public int kthSmallest(TreeNode root, int k) { return helper(root, k).val; } public TreeNode helper(TreeNode root, int k) { if (root == null) { return null; } TreeNode left = helper(root.left, k); if (left != null) { return left; } count++; if(count == k) { return root; } return helper(root.right, k); } public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length == 0) { return null; } int r = pre[0]; int index = 0; for(int i=0; i= arr.length || node.val != arr[index]) { return false; } if(node.left == null && node.right == null && index = arr.length - 1) { return true; } return helper(node.left, arr, index + 1) || helper(node.right, arr, index + 1); } int countPaths(Node node, int sum) { List path = new ArrayList<>(); return helper(node, sum, path); } int helper(Node node, int sum, List path) { if(node == null) { return 0; } path.add(node.val); int count = 0; int s = 0; // how many paths I can make ListIterator itr = path.listIterator(path.size()); while (itr.hashPrevious()) { s += itr.previous(); if (s == sum) { count++; } } count += helper(node.left, s, path) + helper(node.right, sum, path); // backtrack path.remove(path.size() - 1); return count; } // put in a list List> findPaths(Node node, int sum) { List> paths = new ArrayList<>(); List path = new ArrayList<>(); helper(node, sum, path); return paths; } void helper(Node node, int sum, List path, List> paths) { if(node == null) { return 0; } path.add(node.val); if (node.val == sum && node.left == null && node.right == null) { paths.add(new ArrayList<>(path)); } else { helper(node.left, sum-node.val, path, paths); helper(node.right, sum-node.val, path, paths); } // backtrack path.remove(path.size() - 1); } } ================================================ FILE: lectures/20-trees/code/Questions/SD.java ================================================ // https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ class SD { public List serialize(Node node) { List list = new ArrayList<>(); helper(node, list); return list; } void helper(Node node, List list) { if (node == null) { list.add("null"); return; } list.add(String.valueOf(node.val)); helper(node.left, list); helper(node.right, list); } Node deserialize(List list) { Collections.reverse(list); Node node = helper2(list); return node; } Node helper(List list) { String val = list.remove(list.size() - 1); if (val.charAt(0) == 'n') { return null; } Node node = new Node(Integer.parseInt(val)); node.left = helper2(list); node.right = helper2(list); return node; } } ================================================ FILE: lectures/20-trees/code/Segment trees/Main.java ================================================ class Main { public static void main(String[] args) { int[] arr = {3, 8, 6, 7, -2, -8, 4, 9}; SegmentTree tree = new SegmentTree(arr); // tree.display(); System.out.println(tree.query(1, 6)); } } ================================================ FILE: lectures/20-trees/code/Segment trees/SegmentTree.java ================================================ class SegmentTree { private static class Node { int data; int startInterval; int endInterval; Node left; Node right; public Node (int startInterval, int endInterval) { this.startInterval = startInterval; this.endInterval = endInterval; } } Node root; public SegmentTree(int[] arr) { // create a tree using this array this.root = constructTree(arr, 0, arr.length - 1); } private Node constructTree(int[] arr, int start, int end) { if(start == end) { // leaf node Node leaf = new Node(start, end); leaf.data = arr[start]; return leaf; } // create new node with index you are at Node node = new Node(start, end); int mid = (start + end) / 2; node.left = this.constructTree(arr, start, mid); node.right = this.constructTree(arr, mid + 1, end); node.data = node.left.data + node.right.data; return node; } public void display() { display(this.root); } private void display(Node node) { String str = ""; if(node.left != null) { str = str + "Interval=[" + node.left.startInterval + "-" + node.left.endInterval + "] and data: " + node.left.data + " => "; } else { str = str + "No left child"; } // for current node str = str + "Interval=[" + node.startInterval + "-" + node.endInterval + "] and data: " + node.data + " <= "; if(node.right != null) { str = str + "Interval=[" + node.right.startInterval + "-" + node.right.endInterval + "] and data: " + node.right.data; } else { str = str + "No right child"; } System.out.println(str + '\n'); // call recursion if(node.left != null) { display(node.left); } if(node.right != null) { display(node.right); } } // query public int query(int qsi, int qei) { return this.query(this.root, qsi, qei); } private int query(Node node, int qsi, int qei) { if(node.startInterval >= qsi && node.endInterval <= qei) { // node is completely lying inside query return node.data; } else if (node.startInterval > qei || node.endInterval < qsi) { // completely outside return 0; } else { return this.query(node.left, qsi, qei) + this.query(node.right, qsi, qei); } } // update public void update(int index, int value) { this.root.data = update(this.root, index, value); } private int update(Node node, int index, int value) { if (index >= node.startInterval&& index <= node.endInterval){ if(index == node.startInterval && index == node.endInterval) { node.data = value; return node.data; } else { int leftAns = update(node.left, index, value); int rightAns = update(node.right, index, value); node.data = leftAns + rightAns; return node.data; } } return node.data; } } ================================================ FILE: lectures/20-trees/code/introduction/BST.java ================================================ class BST { public class Node { private int value; private Node left; private Node right; private int height; public Node(int value) { this.value = value; } public int getValue() { return value; } } private Node root; public BST() { } public int height(Node node) { if (node == null) { return -1; } return node.height; } public boolean isEmpty() { return root == null; } public void insert(int value) { root = insert(value, root); } private Node insert(int value, Node node) { if (node == null) { node = new Node(value); return node; } if (value < node.value) { node.left = insert(value, node.left); } if (value > node.value) { node.right = insert(value, node.right); } node.height = Math.max(height(node.left), height(node.right)) + 1; return node; } public void populate(int[] nums) { for (int i = 0; i < nums.length; i++) { this.insert(nums[i]); } } public void populatedSorted(int[] nums) { populatedSorted(nums, 0, nums.length); } private void populatedSorted(int[] nums, int start, int end) { if (start >= end) { return; } int mid = (start + end) / 2; this.insert(nums[mid]); populatedSorted(nums, start, mid); populatedSorted(nums, mid + 1, end); } public boolean balanced() { return balanced(root); } private boolean balanced(Node node) { if (node == null) { return true; } return Math.abs(height(node.left) - height(node.right)) <= 1 && balanced(node.left) && balanced(node.right); } public void display() { display(this.root, "Root Node: "); } private void display(Node node, String details) { if (node == null) { return; } System.out.println(details + node.value); display(node.left, "Left child of " + node.value + " : "); display(node.right, "Right child of " + node.value + " : "); } } ================================================ FILE: lectures/20-trees/code/introduction/BinaryTree.java ================================================ import java.util.Scanner; class BinaryTree { public BinaryTree() { } private static class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } } private Node root; // insert elements public void populate(Scanner scanner) { System.out.println("Enter the root Node: "); int value = scanner.nextInt(); root = new Node(value); populate(scanner, root); } private void populate(Scanner scanner, Node node) { System.out.println("Do you want to enter left of " + node.value); boolean left = scanner.nextBoolean(); if (left) { System.out.println("Enter the value of the left of " + node.value); int value = scanner.nextInt(); node.left = new Node(value); populate(scanner, node.left); } System.out.println("Do you want to enter right of " + node.value); boolean right = scanner.nextBoolean(); if (right) { System.out.println("Enter the value of the right of " + node.value); int value = scanner.nextInt(); node.right = new Node(value); populate(scanner, node.right); } } public void display() { display(this.root, ""); } private void display(Node node, String indent) { if (node == null) { return; } System.out.println(indent + node.value); display(node.left, indent + "\t"); display(node.right, indent + "\t"); } public void prettyDisplay() { prettyDisplay(root, 0); } private void prettyDisplay(Node node, int level) { if (node == null) { return; } prettyDisplay(node.right, level + 1); if (level != 0) { for (int i = 0; i < level - 1; i++) { System.out.print("|\t\t"); } System.out.println("|------->" + node.value); } else { System.out.println(node.value); } prettyDisplay(node.left, level + 1); } public void preOrder() { preOrder(root); } private void preOrder(Node node) { if (node == null) { return; } System.out.print(node.value + " "); preOrder(node.left); preOrder(node.right); } public void inOrder() { preOrder(root); } private void inOrder(Node node) { if (node == null) { return; } preOrder(node.left); System.out.print(node.value + " "); preOrder(node.right); } public void postOrder() { preOrder(root); } private void postOrder(Node node) { if (node == null) { return; } preOrder(node.left); preOrder(node.right); System.out.print(node.value + " "); } } ================================================ FILE: lectures/20-trees/code/introduction/Main.java ================================================ import java.util.Scanner; public class Main { public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // BinaryTree tree = new BinaryTree(); // tree.populate(scanner); // tree.prettyDisplay(); BST tree = new BST(); int[] nums = { 5, 2, 7, 1, 4, 6, 9, 8, 3, 10 }; tree.populate(nums); tree.display(); } } ================================================ FILE: lectures/21-StringBuffer/code/Main.java ================================================ import java.util.Random; import java.util.Arrays; import java.text.DecimalFormat; class Main { public static void main(String[] args) { // constructor 1 StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); // constructor 2 StringBuffer sb2 = new StringBuffer("Kunal Kushwaha"); // constructor 3 StringBuffer sb3 = new StringBuffer(30); System.out.println(sb3.capacity()); sb.append("WeMakeDevs"); sb.append(" is nice!"); // sb.insert(2, " Rahul "); sb.replace(1, 5, "Kushwaha"); sb.delete(1, 5); // sb.reverse(); String str = sb.toString(); System.out.println(str); int n = 20; String name = RandomString.generate(n); System.out.println(name); // remove whitespaces String sentence = "Hi h hjh hjkso siowi w "; System.out.println(sentence); System.out.println(sentence.replaceAll("\\s", "")); // split String arr = "Kunal,Apoorv,Rahul,Snehal"; String[] names = arr.split(","); System.out.println(Arrays.toString(names)); // rounding off DecimalFormat df = new DecimalFormat("00.0000"); System.out.println(df.format(7.29)); } } ================================================ FILE: lectures/21-StringBuffer/code/RandomString.java ================================================ import java.util.Random; class RandomString { static String generate(int size) { StringBuffer sb = new StringBuffer(size); Random random = new Random(); for (int i=0; i < size; i++) { int randomChar = 97 + (int)(random.nextFloat() * 26); sb.append((char)randomChar); } return sb.toString(); } } ================================================ FILE: lectures/22-large numbers/code/Factorial.java ================================================ import java.math.BigInteger; class Factorial { static BigInteger fact(int num) { BigInteger ans = new BigInteger("1"); for (int i=2; i<= num; i++) { ans = ans.multiply(BigInteger.valueOf(i)); } return ans; } } ================================================ FILE: lectures/22-large numbers/code/Main.java ================================================ import java.math.BigInteger; import java.math.BigDecimal; class Main { public static void main(String[] args) { BD(); } static void BD() { double x = 0.03; double y= 0.04; // double ans = y-x; // System.out.println(ans); BigDecimal X = new BigDecimal("0.03"); BigDecimal Y = new BigDecimal("0.04"); BigDecimal ans = Y.subtract(X); // System.out.println(ans); BigDecimal a = new BigDecimal("456576345675.4546376"); BigDecimal b = new BigDecimal("547634565352.986785764"); // operations System.out.println(b.add(a)); System.out.println(b.subtract(a)); System.out.println(b.multiply(a)); System.out.println(b.pow(2)); System.out.println(b.negate()); // constants BigDecimal con = BigDecimal.ONE; } static void BI() { int a = 30; int b = 67; BigInteger B = BigInteger.valueOf(6); // convert int/long to BI int c = B.intValue(); // convert BI to int BigInteger C = new BigInteger("2345678654325678976543256789"); BigInteger X = new BigInteger("4536789765432"); // constants BigInteger D = BigInteger.TEN; // operations BigInteger s = C.add(X); BigInteger m = C.multiply(X); BigInteger sub = C.subtract(X); BigInteger d = C.divide(X); BigInteger rem = C.remainder(X); if (X.compareTo(C) < 0) { System.out.println("Yes"); } System.out.println(Factorial.fact(100)); } } ================================================ FILE: lectures/23-file handling/code/Input.java ================================================ import java.io.*; class Input { static void input() { try (InputStreamReader isr = new InputStreamReader(System.in)) { System.out.print("Enter some letters:"); int letters = isr.read(); while(isr.ready()) { System.out.println((char) letters); letters = isr.read(); } // isr.close(); System.out.println(); } catch (IOException e) { System.out.println(e.getMessage()); } try (FileReader fr = new FileReader("note.txt")) { int letters = fr.read(); while(fr.ready()) { System.out.println((char)letters); letters = fr.read(); } // fr.close(); System.out.println(); } catch (IOException e) { System.out.println(e.getMessage()); } // byte to char stream and then reading char stream try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("You typed: " + br.readLine()); } catch (IOException e) { System.out.println(e.getMessage()); } try (BufferedReader br = new BufferedReader(new FileReader("note.txt"))) { while (br.ready()) { System.out.println(br.readLine()); } } catch (IOException e) { System.out.println(e.getMessage()); } } } ================================================ FILE: lectures/23-file handling/code/Main.java ================================================ import java.io.*; import java.io.IOException; import java.util.Scanner; class Main { public static void main(String[] args) { // create try { File fo = new File("new-file.txt"); fo.createNewFile(); } catch (IOException e) { System.out.println(e.getMessage()); } // write in the file try { FileWriter fw = new FileWriter("new-file.txt"); fw.write("सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच:"); fw.close(); } catch (IOException e) { System.out.println(e.getMessage()); } // reading from a file try (BufferedReader br = new BufferedReader(new FileReader("new-file.txt"))) { while (br.ready()) { System.out.println(br.readLine()); } } catch (IOException e) { System.out.println(e.getMessage()); } // create try { File fo = new File("random.txt"); fo.createNewFile(); if(fo.delete()) { System.out.println(fo.getName()); } } catch (IOException e) { System.out.println(e.getMessage()); } } } ================================================ FILE: lectures/23-file handling/code/Output.java ================================================ import java.io.*; class Output { static void output() { // output OutputStream os = System.out; // os.write(😍); // range is exceeded try (OutputStreamWriter osw = new OutputStreamWriter(System.out)) { osw.write("Hello World"); osw.write(97); osw.write(10); osw.write('A'); osw.write('\n'); char[] arr = "hello world".toCharArray(); osw.write(arr); // osw.write(😍); } catch (IOException e) { System.out.println(e.getMessage()); } try (FileWriter fw = new FileWriter("note.txt", true)) { fw.write("this should be appended"); } catch (IOException e) { System.out.println(e.getMessage()); } try (BufferedWriter bw = new BufferedWriter(new FileWriter("note.txt"))) { bw.write("Hare Krishna"); } catch (IOException e) { System.out.println(e.getMessage()); } } } ================================================ FILE: lectures/23-file handling/code/new-file.txt ================================================ सर्वधर्मान्परित्यज्य मामेकं शरणं व्रज, अहं त्वां सर्वपापेभ्यो मोक्षयिष्यामि मा शुच: ================================================ FILE: lectures/23-file handling/code/note.txt ================================================ Hare Krishna ================================================ FILE: lectures/23-file handling/notes/notes.txt ================================================ IOException : An IOException is any unexpected problem the JVM encounters while attempting to run a program. When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions. Streams : In its most basic form a stream simply represents a sequence of data (bytes or unicode characters) in some sort of a sequential queue. Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. Java implements streams within class hierarchies defined in the java.io package. The same I/O classes and methods can be applied to different types of devices. Java defines two types of streams: -Byte streams provide a convenient means for handling input and output of bytes. Byte streams contain binary data this useful for things such as reading and writing to files - just imagine opening up an image file in a text editor, that is a good representation of byte data. EXAMPLE : Use a byte stream ex : InputStream etc and type 'ᛞ'. This exceeds the 256 limit of 8-bit characters hence it will show some other value. If we type 'ᛞ' in char-stream such as InputStreamReader it will show 'ᛞ' only. OutputStream os = System.out; os.write('ᛞ'); // will not show anything (or garbage) cuz range exceeded. ᛞ is Unicode. -Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized, good candidate for things like keyboard input and console output. Also, in some cases, character streams are more efficient than byte streams. Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that handle the differences among various devices, such as disk files, network connections, and even memory buffers. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ) Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. Two of the most important methods are read( ) and write( ). The Predefined Streams : System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams. NOTE : Names of character streams typically end with Reader/Writer & names of byte streams end with InputStream/OutputStream. InputStreamReader Class : EXTENDS READER : Abstract class for reading character streams. int read() : The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached Primarily it is used to convert byte streams to character streams. java.io.InputStreamReader has several overloaded constructors with each taking an InputStream (like System.in, or FileInputStream) as the first parameter. The InputStreamReader class has a method called close() that will close the stream and releases any system resources associated with it. The close() method should always be called once you are done with the input stream. In Java 7 a new feature called try-with-resources was introduced. Specifically a resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. How do we know if a class is a resource? Simple, if it implements java.lang.AutoCloseable, the class can be considered a resource. try-with-resources : The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. FileReader Class : The purpose of the FileReader class is to simply read character based files. The FileReader class implements AutoClosable so we can use the try-with-resources type exception handling. It also interesting to note that the FileReader class does not define or override any public methods, so it inherits all of its methods from its superclass InputStreamReader; InputStreamReader is a subclass of Reader which is a subclass of Object and that describes the class hierarchy. Object -> Reader -> InputStreamReader -> FileReader BufferedReader Class : BufferedReader(Reader inputReader) IT EXTENDS READER. HENCE HAS IT'S OWN read() which is same as InputStreamReader. The BufferedReader class is used to read text from a character stream. The BufferedReader class has the same read() method that both InputStreamReader and FileReader use to read a single byte at a time. The BufferedReader class introduces a method named readLine() which will read an entire line of text which is a huge improvement. The BufferedReader class implements AutoClosable so we can use the try-with-resources type exception handling. To obtain a character-based stream that is attached to the console, wrap System.in in a BufferedReader object. InputStreamReader(InputStream inputStream) BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); NOTE : new InputStreamReader(System.in) converts byte stream into char stream. AND then br is reading that char stream. Which is what we want! After this statement executes, br is a character-based stream that is linked to the console through System.in. Writer Classes : OutputStreamWriter Class : EXTENDS WRITER Used to write to character streams. The OutputStreamWriter class implements AutoClosable so we can use the try-with-resources type exception handling. There are only four public methods in the OutputStreamWriter class: close(), flush(), getEncoding(), and write(). The write() method has three overloaded versions : -write(int a) : writes a single character to character stream. Characters being written is contained in 16 lower bits of the ‘char’ integer value, rest of the 16 higher bits are ignored by the method. -write(String str) -write(char cbuf[]) FileWriter Class : EXTENDS OutputStreamWriter The purpose of the FileWriter class is to simply write character based files. The FileWriter class implements AutoClosable so we can use the try-with-resources type exception handling. FileWriter class does not define or override any public methods, so it inherits all of its methods from its superclass OutputStreamWriter. Object -> Writer -> OutputStreamWriter -> FileWriter BufferedWriter Class : The BufferedWriter class is used to write text to a character stream. The BufferedWriter class has three overloaded versions of the write() method. The BufferedWriter class introduces a method named newLine() which means that you will not have to hardcode in the "\r\n" into your output stream anymore. The BufferedWriter class implements AutoClosable so we can use the try-with-resources type exception handling. File Class : Consider this Windows hard coded path represented as a string: "c:\\Java\\BW\\Sample.txt". If a user attempted to run your program on a Linux or UNIX OS, your program will fail miserably. That is because the directory separator is '/' in UNIX as opposed to '\' in Windows. The file class provides us with several tools to dynamically create our directory and file structure. Constructors: File(File parent, String child) File(String pathname) // not very useful for multi-platform File(String parent, String child) File(URI uri) ================================================ FILE: lectures/24-heaps/code/heaps-1/Heap.java ================================================ import java.util.ArrayList; class Heap> { private ArrayList list; public Heap() { list = new ArrayList<>(); } private void swap(int first, int second) { T temp = list.get(first); list.set(first, list.get(second)); list.set(second, temp); } private int parent(int index) { return (index - 1) / 2; } private int left(int index) { return index * 2 + 1; } private int right(int index) { return index * 2 + 2; } public void insert(T value) { list.add(value); upheap(list.size() - 1); } private void upheap(int index) { if(index == 0) { return; } int p = parent(index); if(list.get(index).compareTo(list.get(p)) < 0) { swap(index, p); upheap(p); } } public T remove() throws Exception { if (list.isEmpty()) { throw new Exception("Removing from an empty heap!"); } T temp = list.get(0); T last = list.remove(list.size() - 1); if (!list.isEmpty()) { list.set(0, last); downheap(0); } return temp; } private void downheap(int index) { int min = index; int left = left(index); int right = right(index); if(left < list.size() && list.get(min).compareTo(list.get(left)) > 0) { min = left; } if(right < list.size() && list.get(min).compareTo(list.get(right)) > 0) { min = right; } if(min != index) { swap(min, index); downheap(min); } } public ArrayList heapSort() throws Exception { ArrayList data = new ArrayList<>(); while(!list.isEmpty()) { data.add(this.remove()); } return data; } } ================================================ FILE: lectures/24-heaps/code/heaps-1/Main.java ================================================ import java.util.ArrayList; class Main { public static void main(String[] args) throws Exception{ Heap heap = new Heap<>(); heap.insert(34); heap.insert(45); heap.insert(22); heap.insert(89); heap.insert(76); ArrayList list = heap.heapSort(); System.out.println(list); } } ================================================ FILE: lectures/25-hashmaps/code/Hashmaps introduction/HashMapFinal.java ================================================ import java.util.*; public class HashMapFinal { ArrayList> list; private int size = 0; private float lf = 0.5f; public HashMapFinal() { list = new ArrayList<>(); for(int i=0; i < 10; i++) { list.add(new LinkedList<>()); } } public void put(K key, V value) { int hash = Math.abs(key.hashCode() % list.size()); LinkedList entities = list.get(hash); for (Entity entity : entities) { if(entity.key.equals(key)) { entity.value = value; return; } } if((float)(size) / list.size() > lf) { reHash(); } entities.add(new Entity(key, value)); size++; } private void reHash() { System.out.println("We are now rehashing!"); ArrayList> old = list; list = new ArrayList<>(); size = 0; for(int i=0; i()); } for(LinkedList entries :old) { for(Entity entry : entries) { put(entry.key, entry.value); } } } public V get(K key) { int hash = Math.abs(key.hashCode() % list.size()); LinkedList entities = list.get(hash); for(Entity entity : entities) { if(entity.key.equals(key)) { return entity.value; } } return null; } public void remove(K key) { int hash = Math.abs(key.hashCode() % list.size()); LinkedList entities = list.get(hash); Entity target = null; for(Entity entity : entities) { if(entity.key.equals(key)) { target = entity; break; } } entities.remove(target); size--; } public boolean containsKey(K key) { return get(key) != null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{"); for(LinkedList entities : list) { for(Entity entity : entities) { builder.append(entity.key); builder.append(" = "); builder.append(entity.value); builder.append(" , "); } } builder.append("}"); return builder.toString(); } private class Entity { K key; V value; public Entity(K key, V value) { this.key = key; this.value = value; } } } ================================================ FILE: lectures/25-hashmaps/code/Hashmaps introduction/Main.java ================================================ import java.util.*; class MapUsingHash { private Entity[] entities; public MapUsingHash() { entities = new Entity[100]; } public void put(String key, String value) { int hash = Math.abs(key.hashCode() % entities.length); entities[hash] = new Entity(key, value); // overriding } public String get(String key) { int hash = Math.abs(key.hashCode() % entities.length); if(entities[hash] != null && entities[hash].key.equals(key)) { return entities[hash].value; } return null; } public void remove(String key) { int hash = Math.abs(key.hashCode() % entities.length); if(entities[hash] != null && entities[hash].key.equals(key)) { entities[hash] = null; } } private class Entity { String key; String value; public Entity(String key, String value) { this.key = key; this.value = value; } } } class Main { public static void main(String[] args) { // hashDemo(); HashMapFinal map = new HashMapFinal<>(); map.put("Mango", "King of fruits"); map.put("Apple", "A sweet red fruit"); map.put("Litchi", "Kunal's fav fruit"); System.out.println(map); } public static void hashDemo() { // String name = "Rahul"; // Integer a = 4235678; // int code = a.hashCode(); // System.out.println(code); HashMap map = new HashMap<>(); map.put("Kunal", 89); map.put("Karan", 99); map.put("Rahul", 94); // System.out.println(map.get("Karan")); // System.out.println(map.getOrDefault("Apoorv", 78)); System.out.println(map.containsKey("Karan")); HashSet set = new HashSet<>(); set.add(56); set.add(9); set.add(12); set.add(43); set.add(56); set.add(2); System.out.println(set); } } ================================================ FILE: lectures/25-hashmaps/code/KarpRabin/KarpRabin.java ================================================ public class KarpRabin { private final int PRIME = 101; private double calculateHash(String str) { double hash = 0; for(int i=0; i < str.length(); i++) { hash += str.charAt(i) * Math.pow(PRIME, i); } return hash; } private double updateHash(double prevHash, char oldChar, char newChar, int patternLength) { double newHash = (prevHash - oldChar) / PRIME; newHash = newHash + newChar * Math.pow(PRIME, patternLength - 1); return newHash; } public void search(String text, String pattern) { int patternLength = pattern.length(); double patternHash = calculateHash(pattern); double textHash = calculateHash(text.substring(0, patternLength)); for(int i=0; i<= text.length() - patternLength; i++) { if(textHash == patternHash) { if(text.substring(i, i+patternLength).equals(pattern)) { System.out.println("Pattern found at index " + i); } } if (i < text.length() - patternLength) { textHash = updateHash(textHash, text.charAt(i), text.charAt(i + patternLength), patternLength); } } } } ================================================ FILE: lectures/25-hashmaps/code/KarpRabin/Main.java ================================================ class Main { public static void main(String[] args) { KarpRabin algo = new KarpRabin(); algo.search("ApoorvKunalRahul", "Kunal"); } } ================================================ FILE: lectures/26-advance-sorting/CountSort/Main.java ================================================ import java.util.*; class Main { public static void countSort(int[] array) { if(array == null || array.length <= 1) { return; } int max = array[0]; for(int num : array) { if(num > max) { max = num; } } int[] countArray = new int[max + 1]; for(int num : array) { countArray[num]++; } int index = 0; for(int i=0; i<= max; i++) { while(countArray[i] > 0) { array[index] = i; index++; countArray[i]--; } } } public static void countSortHash(int[] arr) { if(arr == null || arr.length <= 1) { return; } int max = Arrays.stream(arr).max().getAsInt(); int min = Arrays.stream(arr).min().getAsInt(); Map countMap = new HashMap<>(); for(int num : arr) { countMap.put(num, countMap.getOrDefault(num, 0) + 1); } int index = 0; for(int i=min; i<=max; i++) { int count = countMap.getOrDefault(i, 0); for(int j=0; j < count; j++) { arr[index] = i; index++; } } } public static void main(String[] args) { int[] arr = {6, 3, 10, 9, 2, 4, 9, 7}; countSortHash(arr); System.out.println(Arrays.toString(arr)); } } ================================================ FILE: lectures/26-advance-sorting/RadixSort/Main.java ================================================ import java.util.*; class Main { public static void radixSort(int[] arr) { int max = Arrays.stream(arr).max().getAsInt(); // do count sort for every digit place for(int exp = 1; max/exp > 0; exp *= 10) { countSort(arr, exp); } } private static void countSort(int[] arr, int exp) { int n = arr.length; int[] output = new int[n]; int[] count = new int[10]; Arrays.fill(count, 0); for(int i=0; i=0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } System.out.println("Output array " + Arrays.toString(output)); System.arraycopy(output, 0, arr, 0, n); } public static void main(String[] args) { int[] arr = {29, 83, 471, 36, 91, 8}; System.out.println("Origin array: " + Arrays.toString(arr)); radixSort(arr); System.out.println("Sorted array: " + Arrays.toString(arr)); } } ================================================ FILE: lectures/27-huffman-coding/code/Heap.java ================================================ import java.util.ArrayList; public class Heap>{ private ArrayList list; public Heap(){ list = new ArrayList<>(); } public void insert(T value){ list.add(value); upheap(list.size() - 1); } public int size(){ return list.size(); } private void upheap(int index){ if(index == 0){ return; } int p = parent(index); if(list.get(index).compareTo(list.get(p)) < 0){ swap(index, p); upheap(p); } } public T remove() throws Exception{ if(list.isEmpty()){ throw new Exception("Removing from empty Heap"); } T temp = list.get(0); T last = list.remove(list.size() - 1); if(!list.isEmpty()){ list.set(0, last); downheap(0); } return temp; } private void downheap(int index) { int min = index; int left = left(index); int right = right(index); // check is left < min if(left < list.size() && list.get(min).compareTo(list.get(left)) > 0){ min = left; } // check if right < min if(right < list.size() && list.get(min).compareTo(list.get(right)) > 0){ min = right; } if(min != index){ swap(min, index); downheap(min); } } private void swap(int first, int second) { T temp = list.get(first); list.set(first, list.get(second)); list.set(second, temp); } private int parent(int index){ return (index - 1) / 2; } private int left(int index){ return index * 2 + 1; } private int right(int index){ return index * 2 + 2; } public ArrayList heapSort() throws Exception { ArrayList data = new ArrayList<>(); while(!list.isEmpty()){ data.add(this.remove()); } return data; } } ================================================ FILE: lectures/27-huffman-coding/code/HuffmanCoder.java ================================================ import java.util.*; class HuffmanCoder { HashMap encoder; HashMap decoder; private class Node implements Comparable { Character data; int cost; // frequency Node left; Node right; public Node(Character data, int cost) { this.data = data; this.cost = cost; this.left = null; this.right = null; } @Override public int compareTo(Node other) { return this.cost - other.cost; } } public HuffmanCoder(String feeder) throws Exception { HashMap fmap = new HashMap<>(); for(int i=0; i < feeder.length(); i++) { char cc = feeder.charAt(i); if(fmap.containsKey(cc)) { int ov = fmap.get(cc); ov += 1; fmap.put(cc, ov); } else { fmap.put(cc, 1); } } Heap minHeap = new Heap<>(); Set> entrySet = fmap.entrySet(); for(Map.Entry entry : entrySet) { Node node = new Node(entry.getKey(), entry.getValue()); minHeap.insert(node); } while(minHeap.size() != 1) { Node first = minHeap.remove(); Node second = minHeap.remove(); Node newNode = new Node('\0', first.cost + second.cost); newNode.left = first; newNode.right = second; minHeap.insert(newNode); } Node ft = minHeap.remove(); this.encoder = new HashMap<>(); this.decoder = new HashMap<>(); this.initEncoderDecoder(ft, ""); } private void initEncoderDecoder(Node node, String osf) { if(node == null) { return; } if(node.left == null && node.right == null) { this.encoder.put(node.data, osf); this.decoder.put(osf, node.data); } initEncoderDecoder(node.left, osf+"0"); initEncoderDecoder(node.right, osf+"1"); } public String encode(String source) { String ans = ""; // Bitset can be used: like an array but with a bit at each index for(int i=0; i