├── .DS_Store ├── Concept_Guide ├── .DS_Store ├── COA-interview.md ├── Computer architecture.md ├── Databases.md ├── OS │ ├── 4172-MIDTERM-REV.md │ ├── Network-KernelvsUser.md │ ├── apple-name.md │ ├── gpu.md │ ├── os-concurrency.md │ └── os-quick-overview.md ├── cpp-primer5 │ └── 7-classes.md ├── cpp-version.md ├── cpp.md ├── oracle.md ├── os-concurrency.md ├── software-architecture.md └── system design guide.pdf ├── Leetcode ├── 1d-dynamic-programming.md ├── BFS.md ├── DFS.md ├── Heap-Priority-Queue.md ├── InterviewPrep.md ├── README.md ├── backtrack.md ├── binary-search.md ├── bit-operation.md ├── greedy.md ├── hash-map.md ├── microsoft-ng.md ├── microsoft.md ├── sliding-windows.md ├── stack.md └── two-pointers.md ├── OS └── Network-KernelvsUser.md ├── README.md ├── companys └── compantlist.md ├── cpp ├── 2. C++ Fundamentals.md ├── 3. STL.md ├── CoureMap.md └── I-II-Stream.md ├── learning_path └── infra.md └── open-source └── resources.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LuminaScript/CS_Interview_Prep_Guide/ac78e73834d646fd5dbb06db7dd64b4ab8af6811/.DS_Store -------------------------------------------------------------------------------- /Concept_Guide/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LuminaScript/CS_Interview_Prep_Guide/ac78e73834d646fd5dbb06db7dd64b4ab8af6811/Concept_Guide/.DS_Store -------------------------------------------------------------------------------- /Concept_Guide/COA-interview.md: -------------------------------------------------------------------------------- 1 | 1. **Introduction to Computer Architecture** 2 | 3 | - What is computer architecture? 4 | 5 | - What are the three categories of computer architecture? 6 | 7 | - **System Design** 8 | 9 | - Includes all hardware components in the system such as: 10 | 11 | - Data processors 12 | - Direct memory access 13 | - Graphics processing unit 14 | 15 | - Data paths 16 | - Memory controllers 17 | - Miscellaneous aspects such as virtualization and multiprocessing 18 | 19 | - **Instruction Set Architecture (ISA)** 20 | 21 | - Part of the central processing unit visible to compiler writers and programmers 22 | - Defines the CPU's capabilities and functions based on: 23 | - What programming it can process and perform 24 | - Includes data formats, memory addressing modes, processor register types, word size 25 | - The instruction set that programmers use 26 | 27 | - **Microarchitecture** 28 | 29 | - Defines: 30 | - Storage elements 31 | - Data processing and data paths 32 | - Details how these elements should be implemented in the ISA 33 | 34 | 2. **Components and Functionality** 35 | 36 | - What are some of the components of a microprocessor/CPU? 37 | 38 | ![Screenshot 2024-03-13 at 12.01.24 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-13 at 12.01.24 PM.png) 39 | 40 | - **Control Unit**: reads the instructions, and generates the necessary digital signals to operate the other components. 41 | - **I/O Units**: communicate with the rest of the computer system 42 | - **Arithmetic Logic Unit (ALU)**: performs arithmetic operations 43 | - **Storage Unit**: 44 | - **Registers**: Holds a piece of info, such as a computer instruction or the storage address of any particular information, etc. 45 | - **Cache**: The cache memory stores all the frequently used data and instructions of a device in it. Thus, it speeds up the overall performance and process of the computer 46 | 47 | - **What is MESI?** 48 | 49 | - MESI stands for the four states of the cache blocks, which are Modified, Exclusive, Shared and Invalid. 50 | - It's also known as the "Illinois protocol". It's used to maintain cache coherency in hierarchical memory systems. 51 | 52 | - **What are the different types of fields that are part of instruction?** 53 | 54 | - **Example:** "*An instruction is like a command to a computer to perform a particular operation. The instruction format is composed of various fields in them such as:* 55 | - **Operation code field.** *Also called the "op-code field", this field is used to specify the operation to be performed for the instruction.* 56 | - **Address field.** *As the term implies, this field is used to designate the various addresses, such as memory address and register address.* 57 | - **Mode field.** *This field specifies as to how an operand performs or how effective an address is."* 58 | - Imagine an instruction meant to add two numbers, where one number is stored in register R1 and the other is directly provided in the instruction (immediate value). The instruction might look something like this in a simplified form: 59 | - **Op-code field**: "ADD" (indicating addition operation) 60 | - **Address field #1**: "R1" (indicating the first operand is in register R1) 61 | - **Address field #2**: "5" (immediate value to be added to the contents of R1) 62 | - **Mode field for Address field #1**: "Register" (indicating the operand is in a register) 63 | - **Mode field for Address field #2**: "Immediate" (indicating the operand is directly provided in the instruction) 64 | 65 | - **What are the steps involved in an instruction cycle?** 66 | 67 | - **Example:** *"A program that resides in the memory contains a set of instructions that the computer needs to perform sequentially. The cycle for every instruction is called the instruction cycle, which consists of the following steps:* 68 | - **Fetch instruction.** *The CPU fetches the instruction from the memory. The computer gets loaded with the address of the instruction.* 69 | - **Decode.** *This allows the CPU to determine what instruction must be performed and how many operands are needed to fetch to perform an instruction.* 70 | - **Execute.** *At this step, the instruction is performed. If the instruction has logic or arithmetic, the ALU is utilized. This is the only step of the instruction cycle that's useful from the end user's perspective."* 71 | 72 | - **What are flip-flops?** 73 | 74 | - *Flip-flops, also called "latches", are electronic circuits that have two stable states used to store binary data. The data stored in the states can be modified by using varying inputs. Flip-flops are fundamental components of digital electronic systems used in communications, computers and many other kinds of systems.* 75 | 76 | 3. **Performance and Efficiency Enhancements** 77 | 78 | - **What are the different hazards?** 79 | - structural hazards, which occur from resource conflicts when the hardware can't support all possible combinations of instructions in synchronized overlapped execution; 80 | - data hazards, which occur when instructions that manifest data dependence change data in different stages of a pipeline; 81 | - control hazards, which occur from the pipelining of branches and other instructions that modify the PC. 82 | - **What is pipelining?** 83 | - the process of collecting instruction from the processor through a pipeline. It stores and executes instructions in an orderly process 84 | - **What are the five stages in a DLX pipeline?** 85 | - **What is the write-through method?** 86 | 87 | 4. **Memory Management and Storage** 88 | 89 | - **What is a virtual memory on a computer?** 90 | - virtual memory is where MM store the memory from RAM 91 | - **What is a RAID system?** 92 | - RAID – or Redundant Array of Independent Disks – is a type of storage that writes data across multiple drives within the same system. 93 | - **What is a cache?** 94 | - A cache is a small amount of memory, which is a part of the CPU. It's placed closer to the CPU than the RAM. It temporarily holds data and instructions that the CPU is likely to reuse. 95 | - **What is the easiest way to determine cache locations in which to store memory blocks?** 96 | - Direct Mapping: maps each block of MM into one one possible cache line 97 | 98 | 5. **Communication and Synchronization** 99 | 100 | - **What is a snooping protocol?** 101 | - **Def**: A snooping protocol relies on a shared bus that connects all the caches and the main memory. Whenever a processor writes to its cache, it broadcasts the address of the modified block to the bus. Other processors that have a copy of the same block in their caches can either invalidate or update it, depending on the protocol variant. 102 | - **Pros**: simplet & fast 103 | - **Cons**: 104 | - the bus can become a bottleneck as the number of processors and cache accesses increase. 105 | - the protocol requires all the caches to monitor the bus constantly, which consumes power and bandwidth. 106 | - the protocol is not suitable for distributed systems, where the bus is replaced by a network. 107 | - **Interrupts in a microprocessor system** 108 | - **Def**: An interrupt is a signal from a device attached to a computer or from a program within the computer that requires the OS to stop and figure out what to do next. 109 | - **Hardware interrupt**: generated by external devices and I/O devices (e.g. keyboard press ^C) 110 | - Maskable interrupt: can be delayed when a highest priority interrupt has occurred to the processor. 111 | - Non maskable interrupt: cannot be delayed 112 | - **Software interrupt**: generated when internal devices and software programs need to access any system call 113 | - Normal interrupt: caused by the software instructions 114 | - Exception: unplanned interruption when executing a program 115 | - Processor handle interrupts 116 | - **What's the difference between interrupt service routine and subroutine?** 117 | - **What are the two hardware methods to establish a priority? Explain each method.** 118 | - **Daisy-chaining** is a method that involves connecting all the devices that can request an interrupt in a serial manner. This setting is governed by the priority of the devices, in which the device with the highest priority is placed first. 119 | - **Parallel priority**, on the other hand, uses a register for which bits are configured separately by the interrupt signal from each device. It may also come with a mask register, which is used to control the status of each interrupt request. 120 | - **What does wait state mean?** 121 | - A wait state means that the computer processor experiences a delay when accessing a device or an external memory that is slow in its response. 122 | - Wait states are considered wasteful in processor performance, which is why modern-day designs try to either minimize or eliminate wait states. These include pipelines, instruction pre-fetch and pipelines, caches, branch prediction and simultaneous multithreading. While these techniques can't eliminate wait states, they can significantly minimize the problem when they work together. 123 | - **What is a DMA?** 124 | - DMA, which stands for Direct Memory Access, is a feature of computer systems that allows an input/output device to receive or send data directly from or to the main memory, bypassing the CPU to boost memory operations. 125 | - The process is performed by a chip known as the DMA controller. 126 | 127 | 6. **Programming and Instruction Set Architecture** 128 | 129 | - Can you state some of the common rules of assembly language? 130 | - What are the different types of micro-operations? 131 | - **Example:** *"Micro-operations are executed on data stored in registers. They are basic math operations performed on the information stored in one or more registers. The types of micro-operations are:* 132 | - **Shift micro-operations:** *They perform shift operations on data stored in registers.* 133 | - **Logic micro-operations:** *They execute bit manipulation operations on nonnumerical data saved in registers.* 134 | - **Arithmetic micro-operations:** *They perform arithmetic operations, such as subtractions and additions, on digital data stored in registers.* 135 | - **Register transfer micro-operations:** *They transfer binary information between registers."* 136 | - **What is associate mapping?** 137 | - *The associative mapping technique uses several mapping functions to transfer data from the main memory to the cache memory. This means that any main memory is mapped into any line of the cache. As a result, the cache memory address is not in use. The associative cache controller processes and interprets the request by utilizing the main memory address format.* 138 | 139 | 7. **Microarchitecture** 140 | 141 | - What is horizontal microcode? 142 | - In horizontal microcode, each micro-operation is represented by one bit in each microinstruction. Horizontal microcode is generally included in a fairly wide control save it is not exceptional for each work to be 56 bits or more. On each click of a sequencer clock, a microcode word is read, decoded, and used to control the functional components which create up the CPU. The micro-operations and their mnemonics are shown in the table. -------------------------------------------------------------------------------- /Concept_Guide/Databases.md: -------------------------------------------------------------------------------- 1 | ## RDBMS and DBMS 2 | 3 | <<<<<<< Updated upstream 4 | ### Basic Definitions: 5 | - **Databases**: an organized collection of related data where data is stored and organized to serve some specific purpose 6 | - **DBMS (Database Management System)**: a collection of applicaton programs which allow the user to organize, restore and retrieve information about data efficiency and as effectively as possible (e.g. MySql, Oracle, Sybase, etc) 7 | - **RDBMS (Relational Database Management System)**: based on a relational model of dtaa that is stored in database in separate table & related to the use of a common column. Data easily accessed using SQL (Structural Query Language) 8 | ### Data & Databases: 9 | - **Data Redundancy**: duplication of data, causing (1) wastage of storage space; and (2) destruction of the database integrity 10 | - **Types of Relationship in Database**: 11 | ======= 12 | - **Basic Definitions:** 13 | - Databases: an organized collection of related data where data is stored and organized to serve some specific purpose 14 | - DBMS (Database Management System): a collection of applicaton programs which allow the user to organize, restore and retrieve information about data efficiency and as effectively as possible (e.g. MySql, Oracle, Sybase, etc) 15 | - RDBMS (Relational Database Management System): based on a relational model of dtaa that is stored in database in separate table & related to the use of a common column. Data easily accessed using SQL (Structural Query Language) 16 | - **Data & Databases**: 17 | - Data Redundancy: duplication of data, causing (1) wastage of storage space; and (2) destruction of the database integrity 18 | - Types of Relationship in Database: 19 | >>>>>>> Stashed changes 20 | - **One-to-one**: A one-to-one relationship exists when each record in one table corresponds to exactly one record in another table. 21 | - **One-to-many**: A one-to-many relationship occurs when a single record in one table can be associated with one or multiple records in another table. 22 | - **Many-to-many**: In a many-to-many relationship, any record in one table can be related to one or more records in another table and vice versa. 23 | - **Terminologies**: 24 | - **Record**: Record is a collection of values or fields of a specific entity. **For Example,** An employee, Salary account, etc. 25 | - **Field**: A field refers to an area within a record that is reserved for specific data. 26 | - **For Example,** Employee ID. 27 | - **Table**: Table is the collection of records of specific types. 28 | - **For Example,** the Employee table is a collection of records related to all the employees. 29 | 30 | 31 | 32 | ## SQL (Structured Query Language) 33 | 34 | > - **SQL Basics and Commands**: Covers SQL's role, DDL (Data Definition Language), DML (Data Manipulation Language), and DCL (Data Control Language) commands, including their definitions and purposes. 35 | > - **Query Optimization**: Questions related to index hunting and improving query performance delve into the efficiency of data retrieval and manipulation. 36 | 37 | - **Definition**: SQL is an standard programming language that is designed for storing & managing the data in RDBMS using all kinds of data operations. 38 | - **SQL Statements:** 39 | - DDL (Data Definition Language): define the structure that holds the data & auto-committed + changes on DB saved permanently 40 | - Commands 41 | - CREATE to create a new table or database. 42 | - ALTER for alteration. 43 | - TRUNCATE to delete data from the table. 44 | - DROP to drop a table. 45 | - RENAME to rename a table. 46 | - DML (Data Manipulation Language): manipulates data of the database & not auto-committed + can be rolled back 47 | - Commands: 48 | - INSERT to insert a new row. 49 | - UPDATE to update an existing row. 50 | - DELETE to delete a row. 51 | - MERGE for merging two rows or two tables 52 | - **DML Compiler**: DML in query langauge -> Low Level Instruction (that Query Evaulation Enginene understands 53 | - DCL (Data Control Language): control the visibility of the data in the DB (e.g. revoke access permission for using data in the database) 54 | - Commands: 55 | - COMMIT to permanently save. 56 | - ROLLBACK to undo the change. 57 | - SAVEPOINT to save temporarily. 58 | - **DDL Interpreter**: (1) interprets the DDL statements (2) records the generated statemenets in the table containing metadata 59 | 60 | ## Database Design and Normalization 61 | 62 | > - **Normalization Forms**: Discusses various normalization forms (1NF, 2NF, 3NF, BCNF) and their significance in reducing redundancy and improving database design. 63 | > - **Conceptual Design**: Questions on E-R models, entity, entity types, and relationships focus on the conceptual design of databases. 64 | 65 | - **Definition of Normalization & De-normalization**: 66 | - **Normalization**: removing redundant data from teh database by splitting the table in a well-defined manner in order to maintain data integrity 67 | - First Normal Form (1NF): all entities of the table contain unique/atomic values 68 | - Second Normal Form (2NF): in 1NF & non-key attrtbiute of the table is fully dependent on the primary key 69 | - Third Normal Form (3NF): in 3NF & every non-key attribute of the able is not transitively dependent on the primary key 70 | - Boyce Code Normal Form (BCNF): higher version of 3NF & does jot have any multiple overlappijg candidate keys. 71 | - **De-normalization**: adding up redundant data on the table to speed up the complex queries and thus achieve better performance 72 | 73 | - **Conceptual Design**: 74 | 75 | - Functional Dependency: 76 | 77 | - Definition: A relation is said to be in functional dependency when one attribute uniquely defines another attribute. 78 | 79 | - T1[X]=T2[X] and T1[Y]=T2[Y] 80 | - the value of component X uniquely define the value of component Y. 81 | - X->Y means Y is functionally dependent on X. 82 | 83 | - When is functional dependency said to be fully dunctional dependent 84 | 85 | - To fulfill the criteria of fully functional dependency, the relation must meet the requirement of functional dependency. 86 | 87 | A functional dependency ‘A’ and ‘B’ are said to be fully functional dependent when removal of any attribute say ‘X’ from ‘A’ means the dependency does not hold anymore. 88 | 89 | - **E-R model**: an Entity-Relationship model which defines the conceptual view of the database. shows the real-world entities and their association/relations. Entities here represent the set of attributes in the database. 90 | 91 | - **Def'n**: 92 | 93 | - **Entity** can be anything, be it a place, class or object which has an independent existence in the real world. 94 | - **Entity Type** represents a set of entities that have similar attributes. 95 | - **Entity Set** in the database represents a collection of entities having a particular entity type. 96 | - Weak Entity Set: Weak Entity set is the one whose primary key comprises its partial key as well as the primary key of its parent entity. This is the case because the entity set may not have sufficient attributes to form a primary key. 97 | 98 | - **Attribute vs Relation**: 99 | 100 | - **Attribute** is described as the properties or characteristics of an entity. **For Example**, Employee ID, Employee Name, Age, etc., can be attributes of the entity Employee. 101 | - **Relation** is a two-dimensional table containing a number of rows and columns where every row represents a record of the relation. Here, rows are also known as ‘Tuples’ and columns are known as ‘Attributes’. 102 | 103 | - **VDL vs SDL**: 104 | 105 | - **VDL** is View Definition Language which represents user views and their mapping to the conceptual schema. 106 | - **SDL** is Storage Definition Language which specifies the mapping between two schemas. 107 | 108 | - Cursor: 109 | 110 | - **Implicit cursors** are declared automatically when DML statements like INSERT, UPDATE, DELETE is executed. 111 | - **Explicit cursors** have to be declared when SELECT statements that are returning more than one row are executed. 112 | 113 | - Database Transaction: Sequence of operation performed which changes the consistent state of the database to another is known as the database transaction. After the completion of the transaction, either the successful completion is reflected in the system or the transaction fails and no change is reflected. 114 | 115 | - Database Lock: Database lock basically signifies the transaction about the current status of the data item i.e. whether that data is being used by other transactions or not at the present point of time. There are two types of Database lock: **Shared Lock** and **Exclusive Lock.** 116 | 117 | - Data Warehousing: The storage as well as access to data, that is being derived from the transactions and other sources, from a central location in order to perform the analysis is called Data Warehousing. 118 | 119 | 120 | ## Data Integrity and Transactions 121 | 122 | > - **Atomicity, Consistency, Isolation, Durability (ACID) Properties**: Includes atomicity and its significance in transaction management. 123 | > - **Database Transactions**: Examines the definition, importance, and characteristics of database transactions. 124 | 125 | - **Data Independence**: ability to modify the schema definition in one level in such a way thatt it does not affect the shcema definition in the next higher level. 126 | 127 | - **Hirechies**: physical -> conceptual -> view 128 | 129 | - Physical Data Independence: It modifies the schema at the physical level without affecting the schema at the conceptual level. 130 | - Logical Data Independence: It modifies the schema at the conceptual level without affecting or causing changes in the schema at the view level. 131 | 132 | - **View vs Data Independece**: View is a virtual table that does not have its data on its own rather the data is defined from one or more underlying base tables. 133 | 134 | Views account for logical data independence as the growth and restructuring of base tables are not reflected in views. 135 | 136 | - Advantages 137 | - As there is no physical location where the data in the view is stored, it generates output without wasting resources. 138 | - Data access is restricted as it does not allow commands like insertion, updation, and deletion. 139 | - Disadvantages: 140 | - The view becomes irrelevant if we drop a table related to that view. 141 | - Much memory space is occupied when the view is created for large tables. 142 | 143 | ## Advanced Database Concepts 144 | 145 | - **Data Warehousing**: Explores the concept, advantages, and importance of data warehousing in analytical processing and decision-making. 146 | 147 | - **Database Partitioning**: Discusses the process and significance of database partitioning for performance improvement and manageability. 148 | 149 | - **Join**: the process of deriving the relationship between different tables by combining columns from one or more tables having common values in each. When a table joins with itself, it is known as Self Join. 150 | 151 | - **Index hunting**: the process of boosting the collection of indexes which helps in improving the query performance as well as the speed of the database. 152 | 153 | - **improve query performance using Index hunting?** 154 | 155 | - Using a query optimizer to coordinate queries with the workload. 156 | 157 | - Observing the performance and effect of index and query distribution. 158 | 159 | - ‘**Cluster**’ vs ‘**Non-cluste**r’ index. 160 | 161 | - Clustered index alters the table and re-order the way in which the records are stored in the table. Data retrieval is made faster by using the clustered index. 162 | 163 | - A Non-clustered index does alter the records that are stored in the table but creates a completely different object within the table. 164 | 165 | - **disadvantages of a Query** 166 | 167 | - Indexes are not present. 168 | - Stored procedures are excessively compiled. 169 | - Difficulty in interfacing. 170 | 171 | - **Fragmentation** 172 | 173 | a feature that controls the logical data units, also known as fragments that are stored at different sites of a distributed database system. 174 | 175 | ## Database Security and Administration 176 | 177 | - **Database Locks**: Different types of database locks and their roles in concurrency control. 178 | - **Backup and Recovery**: Checkpoints and their importance in database recovery and maintenance. 179 | 180 | <<<<<<< Updated upstream 181 | ======= 182 | 183 | 184 | **Q #31) What do you understand by Join?** 185 | 186 | **Answer:** Join is the process of deriving the relationship between different tables by combining columns from one or more tables having common values in each. When a table joins with itself, it is known as Self Join. 187 | 188 | **Q #32) What do you understand by Index hunting?** 189 | 190 | **Answer:** Index hunting is the process of boosting the collection of indexes which helps in improving the query performance as well as the speed of the database. 191 | 192 | **Q #33) How to improve query performance using Index hunting?** 193 | 194 | **Answer: Index hunting help in improving query performance by:** 195 | 196 | - Using a query optimizer to coordinate queries with the workload. 197 | - Observing the performance and effect of index and query distribution. 198 | 199 | **Q #34) Differentiate between ‘Cluster’ and ‘Non-cluster’ index.** 200 | 201 | **Answer:** Clustered index alters the table and re-order the way in which the records are stored in the table. Data retrieval is made faster by using the clustered index. 202 | 203 | A Non-clustered index does alter the records that are stored in the table but creates a completely different object within the table. 204 | 205 | **Q #35) What are the disadvantages of a Query?** 206 | 207 | **Answer: Disadvantages of a Query are:** 208 | 209 | - Indexes are not present. 210 | - Stored procedures are excessively compiled. 211 | - Difficulty in interfacing. 212 | 213 | **Q #36) What do you understand by Fragmentation?** 214 | 215 | **Answer:** Fragmentation is a feature that controls the logical data units, also known as fragments that are stored at different sites of a distributed database system. 216 | >>>>>>> Stashed changes 217 | -------------------------------------------------------------------------------- /Concept_Guide/OS/apple-name.md: -------------------------------------------------------------------------------- 1 | Apple Questions 2 | 3 | > Hi Yizhen, 4 | > 5 | > We are hiring Software Engineers onto our Networking Group in both San Diego and Cupertino. These teams work on the core networking stack OS components used in the majority of Apple's platforms - focusing on compromise between performance (throughput and latency), energy efficiency (CPU and memory usage), ease of use and security. It is a mix of kernel and userspace networking infrastructure. 6 | > 7 | > We are looking for SW Engineers at all levels and looking for people more interested in solving kernel problems. 8 | > 9 | > This team owns technologies like Kernel Bypass, Offloading, TCP/IP stack, Skywalk, InternetSharing, IPSec, DPDK, RDMA and actively engage with HW teams to co-design HW/SW systems that works more efficiently. 10 | > 11 | > Are you open to an exploratory 15 minute call? Looking forward to hearing from you. 12 | > 13 | > Thank you, 14 | 15 | - what linux kernel is working on? latest 16 | - What part of the OS is more emphasize in the work? memory - schedulin and networking> 17 | - Kernel-bypass: 18 | - networking eliminates the overheads of in-kernel network stacks by moving protocol processing to userspace. 19 | - curious -> elaborate a bit more on the implementation detail 20 | 21 | - InternetSharing 22 | - Internet Connection Sharing is a Windows service that enables one Internet-connected computer to share its Internet connection with other computers on a local area network. 23 | -------------------------------------------------------------------------------- /Concept_Guide/OS/gpu.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### GPU vs CPU 4 | 5 | GPUs (Graphics Processing Units) and CPUs (Central Processing Units) are both critical components of computer systems but serve different purposes. CPUs are designed to handle a wide range of computing tasks, including running the operating system and most applications. They excel in serial processing, where tasks are executed one after another. GPUs, on the other hand, are specialized processors designed to accelerate graphics rendering and are optimized for parallel processing, where many calculations are carried out simultaneously. This makes GPUs particularly effective for tasks requiring high computational throughput, such as machine learning, scientific simulations, and graphics rendering. 6 | 7 | ### Writing and Compiling CUDA C++ Code 8 | 9 | CUDA C++ code is written using the CUDA extensions to the C++ language, allowing direct access to GPU's parallel computing architecture. CUDA code typically involves defining kernels, which are functions that run on the GPU. These kernels are executed across many parallel threads. To write CUDA code, you need to include the appropriate CUDA libraries and use the `nvcc` compiler (NVIDIA CUDA Compiler) to compile the code. The `nvcc` compiler translates CUDA C++ code into binary code that can run on the GPU. This process involves specifying the compute capabilities of the target GPU to optimize the performance of the generated binary. 10 | 11 | 12 | 13 | **PDDP Algorithm & Box Constraints** 14 | 15 | - The article discusses optimizing **Parallel Differential Dynamic Programming** (PDDP) for CUDA C++, focusing on implementing and improving robotic motion algorithms. 16 | 17 | - **Box constraints** 18 | Specify bounds for variables in optimization problems, are mentioned as part of the broader discussion on incorporating constraints into the algorithm. 19 | 20 | Box constraints in the context of robotic algorithms, such as those discussed for the Parallel Differential Dynamic Programming (PDDP) approach, specify the **upper** and **lower** bounds for variables within optimization problems. 21 | 22 | These constraints are crucial for ensuring that the solutions to optimization problems—such as robotic trajectory planning—remain within physically feasible or desired ranges. 23 | 24 | In robotic motion algorithms, box constraints are applied to manage variables like joint angles, velocities, or accelerations within specified limits, enhancing the precision and safety of robotic movements. 25 | 26 | By incorporating box constraints, the optimization algorithm can effectively navigate the solution space, ensuring that the computed trajectories do not violate the defined bounds, leading to more reliable and feasible robotic behaviors. 27 | 28 | **Examples**: 29 | Let's assume the robot arm has three joints, and the rotation angle of each joint is represented by the variables *θ1*,*θ*2,*θ*3. The physical limitations of the robot dictate that each joint can only rotate within a specific range: 30 | 31 | > Minimize *f*(*θ*1,*θ*2,*θ*3), the **objective function** representing the criterion to be optimized, such as energy consumption or time. 32 | > 33 | > - Joint 1 (θ1) can rotate between 0° and 180°. 34 | > - Joint 2 (θ2) can rotate between -45° and 45°. 35 | > - Joint 3 (*θ*3) can rotate between -90° and 90°. 36 | 37 | 38 | 39 | ### CUDA/GPU Optimization 40 | 41 | - **The implementation in C++ and CUDA** 42 | C++ aims to enhance simulation precision by optimizing computational techniques: 43 | 44 | - **Minimizing Data Transfer Between Host and Device:** Data transfer between the CPU (host) and GPU (device) is a common bottleneck in GPU-accelerated applications. Minimizing this transfer is crucial for enhancing performance, as it reduces the latency associated with moving data back and forth. This can be achieved by optimizing the algorithm to reduce the frequency and volume of data that needs to be transferred. 45 | 46 | ```cpp 47 | // Pseudo-CUDA code 48 | __global__ void matrixMultiplyKernel(float* A, float* B, float* C, int N) { 49 | // Kernel code to perform matrix multiplication 50 | } 51 | 52 | void matrixMultiply(float* hostA, float* hostB, float* hostResult, int N) { 53 | float *deviceA, *deviceB, *deviceC; 54 | cudaMalloc(&deviceA, size); // Allocate memory on the device 55 | cudaMalloc(&deviceB, size); 56 | cudaMalloc(&deviceC, size); 57 | 58 | // Copy input matrices from host to device once 59 | cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice); 60 | cudaMemcpy(deviceB, hostB, size, cudaMemcpyHostToDevice); 61 | 62 | // Perform matrix multiplication on the device 63 | matrixMultiplyKernel<<>>(deviceA, deviceB, deviceC, N); 64 | 65 | // Copy the result matrix back to the host 66 | cudaMemcpy(hostResult, deviceC, size, cudaMemcpyDeviceToHost); 67 | 68 | // Free device memory 69 | cudaFree(deviceA); 70 | cudaFree(deviceB); 71 | cudaFree(deviceC); 72 | } 73 | 74 | ``` 75 | 76 | 77 | 78 | **Example:** Suppose we have an application that performs a series of matrix multiplications on the GPU. Instead of transferring the intermediate results back to the host after each multiplication, we can design the algorithm to keep these intermediate results on the device until all calculations are complete. This approach minimizes the data transfer, as only the initial and final results are transferred between the host and device. 79 | 80 | - **Avoiding Unnecessary Kernel Launches:** Each kernel launch incurs overhead, including the time it takes to initiate the kernel and synchronize the device with the host. By reducing the number of kernel launches, you can decrease this overhead, thus improving the overall efficiency of the application. This involves designing algorithms that can execute more computations per kernel launch or combining multiple operations into a single kernel when possible. 81 | 82 | **Example:** If an application requires performing a matrix multiplication followed by an element-wise addition, these operations can be combined into a single kernel to avoid launching two separate kernels. 83 | 84 | ```cpp 85 | // Pseudo-CUDA code 86 | __global__ void combinedKernel(float* A, float* B, float* C, float* D, int N) { 87 | // Code to perform both matrix multiplication and element-wise addition 88 | } 89 | ``` 90 | 91 | - **Managing Memory Manually:** Effective memory management is critical in CUDA programming. This includes choosing the appropriate memory type (e.g., global, shared, constant, or texture memory), managing memory allocation and deallocation, and optimizing memory access patterns to reduce latency and avoid memory bandwidth bottlenecks. Proper memory management can significantly impact the performance of CUDA applications. 92 | 93 | **Example:** When performing operations that require shared data among threads, using shared memory can significantly reduce memory access times compared to global memory. 94 | 95 | ```cpp 96 | // Pseudo-CUDA code 97 | __global__ void optimizedKernel(float* A, float* B, float* C, int N) { 98 | __shared__ float sharedData[BlockSize]; 99 | // Use sharedData within the kernel to minimize global memory accesses 100 | } 101 | ``` 102 | 103 | 104 | 105 | ### ADMM algorithms & accelerating convergence in distributed optimization simulations 106 | 107 | 1. **ADMM Algorithm Overview:** The Alternating Direction Method of Multipliers (ADMM) is a powerful algorithm used for optimizing and solving complex problems, especially in distributed optimization. It combines the decomposability of dual ascent methods with the superior convergence properties of the method of multipliers, breaking the problem into smaller sub-problems that can be solved independently and in parallel. This makes it highly suitable for distributed computing environments. ADMM iteratively updates the primal and dual variables, converging to the optimal solution by alternating between solving for each variable while keeping the others fixed, and then updating the Lagrange multipliers. 108 | 2. **Convergence in Distributed Optimization Simulations:** Convergence in distributed optimization refers to the process where iterative algorithms approach an optimal solution across multiple computing nodes or processes. In the context of simulations, this involves ensuring that the distributed components of the simulation, often running in parallel and potentially on different hardware, reach a consensus or an optimal state that satisfies the defined constraints and objectives. Effective convergence is crucial for ensuring the accuracy and reliability of simulation outcomes, especially in applications requiring high precision, such as robotic motion planning. Strategies to achieve convergence include careful algorithm design, synchronization mechanisms, and convergence criteria to ensure that all distributed elements contribute effectively to finding the optimal solution. 109 | 3. **Acceleration of Convergence in Distributed Optimization Simulations**: By implementing these optimizations in CUDA, the convergence of distributed optimization simulations is accelerated through efficient parallel computation. This is achieved by leveraging the GPU's architecture to execute multiple operations simultaneously, significantly reducing the time required for each iteration of the optimization process. The use of parallel processing allows for faster convergence towards optimal solutions by efficiently performing computations that would be time-consuming on a CPU. 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /Concept_Guide/OS/os-quick-overview.md: -------------------------------------------------------------------------------- 1 | # Operating System Basics: 2 | 3 | 1. **What is an operating system?** 4 | - An operating system (OS) is the program that, after being initially loaded into the computer by a boot program, manages all of the other application programs in a computer. 5 | - The application programs make use of the operating system by making requests for services through a defined application program interface ([API](https://www.techtarget.com/searchapparchitecture/definition/application-program-interface-API)). 6 | - In addition, users can interact directly with the operating system through a user interface, such as a command-line interface (CLI) or a graphical UI (GUI). 7 | 2. **Explain the main functions of an operating system.** 8 | 1. **Resource Management**: 9 | - manages the computer's hardware resources: CPU, memory, disk space, input/output devices (such as printers, monitors, and keyboards), and network connections. 10 | - allocates resources to different applications and users as needed, and ensures that they are used efficiently: 11 | - tasks: process scheduling, memory management, and input/output management. 12 | 2. **User Interface**: 13 | - graphical user interfaces (GUIs) 14 | - command-line interfaces (CLIs) 15 | - APIs 16 | 3. **File Management:** 17 | - enables users to store and access data on the computer's storage devices. 18 | - It manages files and directories, and provides utilities for creating, copying, moving, and deleting files. 19 | - File Access Permission 20 | 4. **Security**: 21 | - This includes password protection, access control, antivirus software, and firewall protection. 22 | - The operating system also logs events and activities to track potential security breaches and detect anomalies. 23 | 3. **Describe the difference between a process and a thread:** 24 | - **Resource Allocation**: threads (of the same process) run in a shared memory space, while processes run in separate memory spaces. 25 | - Thread: Threads within the same process share the same memory space and resources, such as file handles and open network connections. This sharing allows for faster communication and data sharing between threads but can also lead to synchronization issues. 26 | - **Communication**: 27 | - Process: Inter-process communication (IPC) is required for processes to communicate with each other. IPC mechanisms include message passing, sockets, and shared memory. 28 | - Thread: Threads within the same process can communicate more easily by sharing variables and data structures directly in memory. This makes thread communication faster and more efficient. 29 | 4. **What are the differences between multiprogramming, multitasking, and multiprocessing?** 30 | 1. **MultiProgramming vs MultiProcessing:** 31 | - **Multiprogramming** focuses on efficient CPU utilization by rapidly switching between processes on a single CPU 32 | - **Multiprocessing** uses multiple CPUs or CPU cores to execute tasks concurrently, achieving true parallelism and higher performance. 33 | 2. **Multitasking –** Multitasking is nothing but multiprogramming with a Round-robin scheduling algorithm. 34 | 3. **Multithreading** is an extension of multitasking. 35 | 5. **Explain the concept of a context switch.** 36 | - CONCEPT: 37 | Context switching involves saving the state of a running process and loading the state of another process to switch between them. 38 | - TRIGGERS: 39 | 1. **Interrupts:** Hardware Interruption through signals 40 | 2. **Multitasking:** Involves switching processes on the CPU, retaining the previous state for seamless execution. (Schedule Algorithm) 41 | 3. **Kernel/User Switch:** transitioning between user mode and kernel mode in OS 42 | 6. **What are the differences between a monolithic kernel and a microkernel?** 43 | - Monolithic kernels house all components in kernel space. 44 | - Microkernels separate core functionalities in kernel space from other services in user space 45 | 7. **Describe the process of process creation and termination.** 46 | - **Process Creation:** 47 | - When a new process is created, the operating system assigns it a unique Process Identifier (PID) and adds an entry to the process table. 48 | - Memory space is allocated for the program, data, stack, and Process Control Block (PCB). PCB is initialized with PID, parent's PID, register values, process state ('New'), and optional priority. 49 | - The process is linked to the scheduling queue, and its state changes to 'Ready,' making it eligible for CPU execution. 50 | 51 | - **Process Deletion:** 52 | 53 | - Processes can terminate in two ways: 54 | - Self-termination: A process finishes executing its last statement and uses the **`exit()`** system call. It returns an exit code (typically 0 for success). 55 | - Termination by the system or parent: 56 | - Parent may terminate a child if the task is no longer needed, the child exceeds resource limits, or the parent process is exiting (cascaded termination). 57 | - Upon termination, OS reclaims resources held by the process, including memory and file buffers. 58 | - Process termination status and execution times are returned to the parent if it is waiting. 59 | - Orphaned processes, which cannot terminate due to an absent parent, are eventually inherited and terminated by the system (zombies). 60 | - use wait() in parent proceed to avoid zombie child process. 61 | 8. **What is the difference between preemptive and non-preemptive scheduling?** 62 | - preemptive scheduling allows the operating system to forcibly switch tasks in a more flexible manner, while non-preemptive scheduling relies on tasks voluntarily releasing the CPU. 63 | - Examples: 64 | - Preemptive: Round Robin, Priority Scheduling, and Multilevel Queue Scheduling 65 | - Non-preemptive: First-Come-First-Served (FCFS) and Shortest Job Next (SJN) scheduling 66 | 9. **What are system calls, and how are they different from normal function calls?** 67 | - Sys Call has more privilege than a normal subroutine. 68 | - Sys Call runs with kernel-mode privilege in the kernel protection domain. 69 | - Sys Call code and data are located in global kernel memory. 70 | 10. **Explain the concept of kernel mode and user mode.** 71 | - Kernel mode/system mode: one of the central processing unit (CPU) operating modes. **While processes run in kernel mode, they have unrestricted access to the hardware.** 72 | - User mode: which is a non-privileged mode for user programs.  73 | **A process running in user mode has limited access to the CPU and the memory.** 74 | 75 | # Process Management: 76 | 77 | 1. **Process State (Five)** 78 | - **New** - The process is in the stage of being created. 79 | - **Ready** The process has all the resources available that it needs to run, but the CPU is not currently working on this process's instructions. 80 | - **Running** The CPU is working on this process's instructions. 81 | - **Waiting** - The process cannot run at the moment, because it is waiting for some resource to become available or for some event to occur. For example the process may be waiting for keyboard input, disk access request, inter-process messages, a timer to go off, or a child process to finish. 82 | - **Terminated -** The process has completed 83 | 84 | 2. **Process Scheduling** 85 | 86 | Process scheduling is crucial for managing how processes are assigned to the CPU. It involves selecting a process from the ready queue and allocating the CPU to it, based on a particular scheduling algorithm. The aim is to optimize system performance metrics like CPU utilization and process turnaround time. 87 | 88 | 3. **Scheduling Algorithms** 89 | 90 | The main scheduling algorithms include: 91 | 92 | - First-Come, First-Served (FCFS) 93 | - Shortest Job First (SJF) 94 | - Priority Scheduling 95 | - Round Robin (RR) 96 | - Multilevel Queue Scheduling 97 | - Multilevel Feedback Queue Scheduling 98 | 99 | 4. **Preemptive vs. Non-Preemptive Scheduling** 100 | 101 | - **Preemptive Scheduling**: Allows the OS to interrupt a running process and reallocate the CPU to another process. 102 | - **Non-Preemptive Scheduling**: A process runs until it completes or blocks, without being preempted by other processes. 103 | 104 | 5. **Context Switch** 105 | 106 | A context switch is the operation of saving and restoring the state of the CPU, so that multiple processes can share a single CPU resource. While necessary for multitasking, frequent context switches can negatively impact system performance. 107 | 108 | 6. **Process Synchronization with Semaphores** 109 | 110 | Process synchronization ensures that multiple processes can operate concurrently without conflicts. Semaphores are a synchronization mechanism that use atomic wait (P) and signal (V) operations to manage access to shared resources, ensuring mutual exclusion and deadlock prevention. 111 | 112 | 7. **The Dining Philosophers Problem** 113 | 114 | This problem illustrates synchronization challenges in concurrent programming. Solutions involve strategies to prevent deadlock and ensure fairness, such as semaphore-based chopstick control or ordering rules for resource acquisition. 115 | 116 | 8. **Critical Section Protection** 117 | 118 | A critical section is a code segment that accesses shared variables and must be executed by only one process or thread at a time. Protection mechanisms include locks, semaphores, and monitors, which enforce mutual exclusion. 119 | 120 | 9. **The Reader-Writer Problem** 121 | 122 | This problem addresses managing access to a shared database among readers and writers. Solutions typically involve read-write locks or semaphores, balancing the need for concurrent read access with exclusive write access. 123 | 124 | 10. **Inter-Process Communication (IPC)** 125 | 126 | IPC mechanisms enable processes to exchange data and synchronize their actions. Common IPC techniques include: 127 | 128 | - Pipes (named and unnamed) 129 | - Message Queues 130 | - Semaphores 131 | - Shared Memory 132 | - Sockets 133 | - Signals 134 | 135 | These mechanisms support various forms of data exchange and coordination among processes, facilitating complex inter-process interactions in modern operating systems. 136 | 137 | # Memory Management: 138 | 1. **Virtual Memory** 139 | 140 | Virtual memory is a memory management capability of an operating system (OS) that uses hardware and software to allow a computer to compensate for physical memory shortages, by temporarily transferring data from random access memory (RAM) to disk storage. This process creates an illusion for users of a very large (virtual) memory space. 141 | 142 | 2. **Paging** 143 | 144 | Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This scheme translates logical addresses into physical addresses by breaking memory into fixed-size blocks called "pages" in logical memory and "frames" in physical memory. Advantages include: 145 | - Elimination of external fragmentation 146 | - More efficient use of memory 147 | - Simplified memory allocation 148 | 149 | 3. **Page Fault** 150 | 151 | A page fault occurs when a program tries to access a page that is mapped in the virtual address space but not loaded in physical memory. The OS handles a page fault by: 152 | - Pausing the program's execution 153 | - Locating the data in secondary storage 154 | - Loading the data into RAM 155 | - Resuming the program's execution 156 | 157 | 4. **Memory Allocation and Deallocation** 158 | 159 | Memory allocation involves assigning a block of physical memory to a process or file. The OS typically provides mechanisms for dynamic allocation and deallocation, allowing programs to request and release memory at runtime to ensure efficient use of resources. 160 | 161 | 5. **Thrashing and Working Set Model** 162 | 163 | Thrashing occurs when a system spends more time processing page faults than executing transactions. The working set model aims to minimize thrashing by keeping all the pages needed by a process's current working set in memory, adjusting the working set size to balance between too many and too few frames. 164 | 165 | 6. **Page Replacement Algorithms** 166 | 167 | Page replacement algorithms decide which memory pages to page out when a page of memory needs to be allocated. Common algorithms include: 168 | - **Least Recently Used (LRU)**: Replaces the page that has not been used for the longest period. 169 | - **First-In, First-Out (FIFO)**: Pages out the oldest page in memory. 170 | - **Optimal**: Replaces the page that will not be used for the longest time in the future. 171 | 172 | 7. **Page Table** 173 | 174 | The page table is a data structure used by the virtual memory system to store the mapping between virtual addresses and physical addresses. Each process has its own page table, which the OS uses to translate logical to physical addresses during execution. 175 | 176 | 8. **Demand Paging** 177 | 178 | Demand paging is a technique where pages are loaded into memory on demand, i.e., only when a page fault occurs. Advantages include: 179 | - Reduced memory consumption 180 | - Faster program start-up 181 | - More efficient use of memory 182 | 183 | 9. **Segmentation Fault** 184 | 185 | A segmentation fault occurs when a program attempts to access an area of memory that it is not allowed to access. The OS handles segmentation faults by terminating the offending process and, typically, reporting an error to the user or system log. 186 | 187 | 10. **Process Swapping** 188 | 189 | Process swapping involves moving a process from main memory to a secondary storage (disk) and back to main memory. It's used to manage the set of active processes in memory, allowing the OS to share the limited resource of physical memory among a large number of processes by swapping them in and out as needed. 190 | 191 | # File Systems 192 | 193 | ### What is a file system, and what are its components? 194 | 195 | A file system is a method and data structure that an operating system uses to control how data is stored and retrieved. Its components include: 196 | 197 | - **File Control Block (FCB)/inode**: Metadata about a file. 198 | - **Directory Structure**: Organizes and provides information about all the files. 199 | - **File Allocation Table**: Tracks the locations of files' data. 200 | - **Data Blocks**: The smallest units of storage containing file data. 201 | 202 | ### Types of File Systems 203 | 204 | - **FAT (File Allocation Table)**: An older, simple system that's widely compatible but lacks features like permissions and security. 205 | - **NTFS (New Technology File System)**: Used by Windows, supporting large volumes, file permissions, and encryption. 206 | - **ext4 (Fourth Extended Filesystem)**: Common in Linux, offering large file sizes and volumes, journaling, and extensibility. 207 | 208 | ### File Allocation and Deallocation 209 | 210 | File allocation involves assigning disk space for files, while deallocation frees that space when files are deleted. Methods include contiguous, linked, and indexed allocation. 211 | 212 | ### File Control Block (FCB) or inode 213 | 214 | An FCB or inode stores metadata about a file, such as its size, permissions, and disk location. It's essential for file system operations. 215 | 216 | ### File Descriptors and Tables 217 | 218 | File descriptors are references to open files, managed per-process in file descriptor tables. They abstract file operations and enable access control. 219 | 220 | ### File Allocation Table (FAT) 221 | 222 | FAT is a filesystem and its data structure that maps file clusters to physical locations on the disk. It simplifies file access but is less efficient for larger disks. 223 | 224 | ### File Allocation Methods 225 | 226 | - **Sequential**: Files are stored in contiguous blocks, easy but can lead to fragmentation. 227 | - **Direct**: Non-contiguous storage, offering flexibility at the cost of complexity. 228 | - **Indexed**: Uses an index block to track file fragments, balancing direct access and fragmentation management. 229 | 230 | ### File Buffering 231 | 232 | File buffering is the process of temporarily holding data in memory during input/output operations, enhancing performance and reducing disk access. 233 | 234 | ### Symbolic Links 235 | 236 | Symbolic links are file system references that point to other files or directories, allowing multiple access paths and simplifying file management. 237 | 238 | ### File Permission Management 239 | 240 | File permissions control read, write, and execute access based on user and group ownership, ensuring security and privacy. 241 | 242 | # Device Management 243 | 244 | ### Device Driver 245 | 246 | A device driver is software that allows the operating system to communicate with hardware devices, abstracting hardware specifics and providing a standard interface. 247 | 248 | ### Device Allocation and Deallocation 249 | 250 | Device allocation grants a process exclusive access to a device, while deallocation releases it, managed by the OS to prevent conflicts. 251 | 252 | ### Device Scheduling Algorithms 253 | 254 | Algorithms optimize device access, examples include First-Come, First-Served (FCFS), Shortest Seek Time First (SSTF), and Elevator (SCAN). 255 | 256 | ### Device Interrupt Handling 257 | 258 | Interrupts signal device status changes, triggering the OS to pause current tasks and execute relevant interrupt service routines (ISRs). 259 | 260 | ### Device Control Block (DCB) 261 | 262 | A DCB stores information about a device's status, configuration, and control, facilitating device management and operations. 263 | 264 | ### Spooling 265 | 266 | Spooling is the process of queuing data for devices, typically printers, allowing for asynchronous data processing and efficient resource use. 267 | 268 | ### Device Registers 269 | 270 | Device registers are small, fast storage locations within hardware devices, used to control operations or store status information. 271 | 272 | ### Polling vs. Interrupt-Driven I/O 273 | 274 | - **Polling**: The CPU repeatedly checks device status, leading to potential inefficiency. 275 | - **Interrupt-Driven I/O**: Devices notify the CPU via interrupts, reducing unnecessary CPU usage. 276 | 277 | ### Device Queue 278 | 279 | Device queues hold requests for devices, managing them efficiently based on scheduling algorithms to optimize access and performance. 280 | 281 | ### Concept of Device Management 282 | 283 | Device management encompasses the processes and mechanisms that control device allocation, operation, and interaction within an OS, ensuring efficient and safe hardware usage. 284 | 285 | -------------------------------------------------------------------------------- /Concept_Guide/cpp-primer5/7-classes.md: -------------------------------------------------------------------------------- 1 | ### 7.1 Define Abstract Data Type 2 | 3 | - **Member function**: 4 | 5 | - Functions defined in the class are implicitly ```inline``` 6 | 7 | - Every members function must be declared inside its class, but can defined outside. 8 | 9 | - ```this```: 10 | 11 | - Every member function access the object on which they is called by ```this``` (constant pointer, cannot changevtye address that ```this``` holds) 12 | 13 | - nonconst object: By default, the type of ```this``` is a const pointer to the nonconst version of the class type. 14 | 15 | - const object: A const following the parameter list indicates that this is a pointer to const. Member functions that use const in this way are **const** **member functions**. 16 | 17 | ```cpp 18 | std::string Sales_data::isbn(const Sales_data *const this) { return this->isbn; } 19 | ``` 20 | 21 | - **Class Scope** 22 | 23 | - Define a member function outside the class: The function name, **Sales_data::avg_price**, uses the **scope operator** 24 | 25 | - Define a Function o Return ```this``` Object: 26 | 27 | ```cpp 28 | Sales_data& Sales_data::combine(const Sales_data &rhs) 29 | { 30 | units_sold += rhs.units_sold; 31 | revenue += rhs.revenue; 32 | return *this; 33 | } 34 | ``` 35 | 36 | - Defining Nonmember Class-Related Functions 37 | 38 | ```cpp 39 | istream &read(istream &is, Sales_data &item) 40 | { 41 | double price = 0; 42 | is >> item.bookNo >> item.units_sold >> price; 43 | item.revenue = price * item.units_sold; 44 | return is; 45 | } 46 | 47 | ostream &print(ostream &os, const Sales_data &item) 48 | { 49 | os << item.revenue << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); 50 | return os; 51 | } 52 | ``` 53 | 54 | 1. both read and write take a **reference** to their respective IO class types. The IO classes are types that cannot be copied, so we may only pass them by reference 55 | 2. reading or writing to a stream changes that stream, so both functions take ordinary references, not references to **const**. 56 | 57 | - **Constructors** 58 | 59 | 1. **The Default Constructor** 60 | 61 | - Default constructors: Classes control default initialization by defining a special constructor. The default constructor is one that takes no arguments. 62 | 63 | ```cpp 64 | Sales_data() = default; 65 | ``` 66 | 67 | 68 | 69 | - Synthesized default constructor: compiler-generatored constructor: 70 | 71 | - If there is an in-class initializer, use it to initialize the member. 72 | - Otherwise, default-initialize the member. 73 | 74 | 2. Constructor Initializer List 75 | 76 | ```cpp 77 | Sales_data(const std::string &s): bookNo(s) { } 78 | Sales_data(const std::string &s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p*n) { } 79 | ``` 80 | 81 | - Constructor initialzier list: ```bookNo(s), units_sold(n), revenue(p*n)``` 82 | 83 | 3. Constructor outside function body 84 | 85 | ```cpp 86 | Sales_data::Sales_data(std::istream &is) 87 | { 88 | read(is, *this); // read will read a transaction from is into this object 89 | } 90 | ``` 91 | 92 | - **Copy, Assignment, and Destruction** 93 | - Objects are copied in several contexts, such as when we initialize a variable or when we pass or return an object by value 94 | - Objects are assigned when we use the assignment operator 95 | - Objects are destroyed when they cease to exist, such as when a local object is destroyed on exit from the block in which it was created 96 | 97 | ### 7.2 Access Control and Encapsulation 98 | 99 | - **Use access specifiers to enforce encapsulation:** 100 | - **public**: Members defined after a **public** specifier are accessible to all parts of the program. The public members define the interface to the class. 101 | - **Private**: Members defined after a **private** specifier are accessible to the member functions of the class but are not accessible to code that uses the class. 102 | - **```class``` vs ```struct``` keywords** 103 | - difference in default access level: 104 | - If we use the struct keyword, the members defined before the first access specifier are public; 105 | - if we use class, then the members are private. 106 | - Paradigm 107 | - when we define a class intending for all of its members to be public, we use struct. 108 | - If we intend to have private members, then we use class. 109 | - **Friends** 110 | - A class can allow another class or function to access its nonpublic members by making that class or function a **friend**. 111 | - A friend declaration only specifies access. It is not a general declaration of the function. If we want users of the class to be able to call a friend function, then we must also declare the function separately from the friend declaration. 112 | 113 | ### 7.3 Additional Class Features 114 | 115 | - **Class Members** **Revisited** 116 | 117 | - Defining a Type Member 118 | 119 | ```cpp 120 | class Screen { 121 | public: 122 | typedef std::string::size_type pos; 123 | private: 124 | pos cursor = 0; 125 | pos height = 0, width = 0; 126 | std::string contents; 127 | }; 128 | ``` 129 | 130 | 1. Type member <=> Type alias ```using pos = std::string::size_type;``` 131 | 132 | 2. Unlike ordinary members, members that define types must appear before they are used. As a result, type members usually appear at the beginning of the class. 133 | 134 | - Making members inline 135 | 136 | - We can explicitly declare a member function as inline as part of its declaration inside the class body. 137 | - Alternatively, we can specify inline on the function definition that appears outside the class body: 138 | 139 | - Overloading Member Functions 140 | 141 | - Mutable Data Members 142 | 143 | ```cpp 144 | class Screen { 145 | public: 146 | void some_member() const; 147 | private: 148 | mutable size_t access_ctr; 149 | }; 150 | 151 | void Screen::some_member() const 152 | { 153 | ++access_ctr; 154 | } 155 | ``` 156 | 157 | - A **mutable** **data member** is never const 158 | - Any member function (including const function) may change a mutable member 159 | 160 | - Initializers for Data Members of Class Type 161 | 162 | ```cpp 163 | class Window_mgr { 164 | private: 165 | std::vector screens{Screen(24, 80, ' ')}; 166 | }; 167 | ``` 168 | 169 | *When we initialize a member of class type, we are supplying arguments to a constructor of that member’s type. In this case, we list initialize our vector member (§ 3.3.1, p. 98) with a single element initializer. That initializer contains a Screen value that is passed to the vector constructor to create a one-element vector. That value is created by the Screen constructor that takes two size parameters and a character to create a blank screen of the given size.* 170 | 171 | - **Functions That Return** ```*this``` 172 | 173 | - Reference return type: 174 | 175 | - reference return type: Functions that return a reference are lvalues, which means that they return the object itself, not a copy of the object. 176 | 177 | ```cpp 178 | inline Screen &Screen::set(pos r, pos col, char ch) 179 | { 180 | contents[r*width + col] = ch; 181 | return *this; 182 | } 183 | ``` 184 | 185 | - non-reference return type: then the return value of function would be a copy of ```*this``` 186 | 187 | - Returning ```*this``` from a const Member Function: 188 | 189 | - A const member function that returns *```this``` as a reference should have a return type that is a reference to const. 190 | 191 | - Overloading Based on ```const``` 192 | 193 | 194 | 195 | 196 | 197 | - **Class Types** 198 | 199 | - Basics: 200 | 201 | - Every class defines a unique type. Two different classes define two different types even if they define the same members. 202 | - We can refer to a class type directly, by using the class name as a type name. Alternatively, we can use the class name following the keyword class or struct: 203 | 204 | - Class Declarations 205 | 206 | - Forward Declaration ``class Screen;`` (Imcommplete Type) 207 | 208 | - Imcommplete Type: After a declaration and before a definition is seen, the type Screen 209 | - Limited Usage: We can define pointers or references to such types, and we can declare (but not define) functions that use an incomplete type as a parameter or return type. 210 | 211 | - A class must be defined—not just declared—before we can write code that creates objects of that type. 212 | 213 | - A class cannot contain members of its own type until it is fully defined, but it can include pointers or references to its own type once its name is declared. 214 | 215 | ```cpp 216 | class Link_screen { 217 | Screen window; 218 | Link_screen *next; 219 | Link_screen *prev; 220 | }; 221 | ``` 222 | 223 | 224 | 225 | ### 7.4 Class Scope 226 | 227 | ### 7.5 Constructors Revisited 228 | 229 | ### 7.6 Static Class Member 230 | 231 | -------------------------------------------------------------------------------- /Concept_Guide/cpp-version.md: -------------------------------------------------------------------------------- 1 | ## CPP Version 2 | 3 | ### C++ 11 4 | 5 | - [Unified Initialization](https://www.geeksforgeeks.org/uniform-initialization-in-c/) 6 | 7 | - [Multithreading](https://www.geeksforgeeks.org/multithreading-in-cpp/) 8 | 9 | - [Smart Pointers](https://www.geeksforgeeks.org/smart-pointers-cpp/) 10 | 11 | - [Hash Tables](https://www.geeksforgeeks.org/hashing-data-structure/) 12 | 13 | - [std::array container](https://www.geeksforgeeks.org/stdarray-in-cpp/) 14 | 15 | - [Move semantics](https://www.geeksforgeeks.org/stdmove-in-utility-in-c-move-semantics-move-constructors-and-move-assignment-operators/) 16 | 17 | - [Lambda functions included](https://www.geeksforgeeks.org/lambda-expression-in-c/) 18 | 19 | - [**auto and decltype**](https://www.geeksforgeeks.org/type-inference-in-c-auto-and-decltype/) added 20 | 21 | 22 | 23 | ### C++ 14 24 | 25 | - [Generalized Lambdas](https://www.geeksforgeeks.org/generalized-lambda-expressions-c14/) 26 | - Reader-Writer Locks 27 | - [**constexpr**](https://www.geeksforgeeks.org/understanding-constexper-specifier-in-c/) included 28 | - Return type deductions extended to all functions 29 | 30 | 31 | 32 | ### C++ 17 33 | 34 | - The file system library and Network concepts included 35 | - Improved Lambdas 36 | - [Fold Expressions](https://www.geeksforgeeks.org/features-of-c17-with-examples/) included 37 | - [Initializers in if and switch statements](https://www.geeksforgeeks.org/c17-new-feature-else-switch-statements-initializers/) 38 | - Concurrent and Parallel algorithms in Standard Template Library(STL) 39 | - [Nested Namespaces](https://www.geeksforgeeks.org/features-of-c17-with-examples/) 40 | - Transactional memory 41 | - Inline Variables 42 | - Optional header file 43 | - Class Template argument deduction(CTAD) 44 | 45 | 46 | 47 | 48 | 49 | Run-time 50 | 51 | ```bash 52 | ubuntu@primary:~/Home$ g++ -std=c++20 helloworld.cpp -o helloworld20 53 | ubuntu@primary:~/Home$ ls 54 | helloworld helloworld.cpp helloworld20 55 | ubuntu@primary:~/Home$ ./helloworld20 56 | Hello, World! 57 | ubuntu@primary:~/Home$ g++ -std=c++23 helloworld.cpp -o helloworld23 58 | ubuntu@primary:~/Home$ ls 59 | helloworld helloworld.cpp helloworld20 helloworld23 60 | ubuntu@primary:~/Home$ g++ -std=c++25 helloworld.cpp -o helloworld25 61 | ``` 62 | 63 | 64 | 65 | ## Linux Version 66 | 67 | 68 | 69 | ## Boost.Asio 70 | 71 | #### Introduction 72 | 73 | Boost.Asio is a C++ library that provides a set of tools for asynchronous I/O, concurrency, and networking. It is a part of the Boost C++ Libraries collection, which is a well-established and widely-used open-source project. Boost.Asio aims to simplify the process of writing asynchronous networked applications while also offering excellent performance. 74 | 75 | #### Features 76 | 77 | 1. **Asynchronous I/O**: Boost.Asio’s asynchronous model allows you to perform I/O operations without blocking the execution of the program. This feature is especially valuable for networking tasks, as it allows the application to handle multiple connections concurrently. 78 | 2. **Networking Protocols**: The library supports a wide range of networking protocols, including TCP, UDP, SSL/TLS, and serial ports. This enables developers to build various networking applications, from simple TCP servers to secure communication channels using SSL/TLS. 79 | 3. **Platform Independence**: Boost.Asio abstracts the platform-specific details, making it easier to write portable networking code that works across different operating systems without modification. 80 | 4. **Error Handling**: The library provides a robust error handling mechanism, which is essential for writing reliable networking applications. Errors are reported through exceptions or error codes, giving developers the flexibility to choose their preferred error-handling approach. 81 | 5. **Timers**: Boost.Asio includes timer functionality, allowing you to schedule tasks to be executed at specific intervals or after a delay. This feature is valuable for implementing time-sensitive operations. 82 | 83 | -------------------------------------------------------------------------------- /Concept_Guide/oracle.md: -------------------------------------------------------------------------------- 1 | ### Experience and Background Questions 2 | 3 | 1. **Oracle**: A multinational computer technology corporation that specializes in developing and marketing database software and technology, cloud engineered systems, and enterprise software products, particularly its own brands of database management systems. 4 | 2. **Familiarity with Oracle**: Describe specific Oracle platforms and programs you've worked with, such as Oracle Database, Oracle Cloud, Oracle ERP, or Oracle Fusion Middleware, and your level of expertise with each. 5 | 3. **Current Work Day**: Outline a typical day, focusing on how you interact with Oracle technologies in your role, including database management, development, or administration tasks. 6 | 4. **Key Roles of Database Management and Development**: Highlight the importance of ensuring data integrity, performance tuning, security, and developing new database systems or enhancing existing ones. 7 | 5. **Specialization with Oracle Technologies**: Discuss your area of expertise within Oracle technologies, such as PL/SQL programming, Oracle Database administration, Oracle Cloud services, etc. 8 | 6. **Ensuring Work Accuracy**: Describe your methods for quality assurance, including code review practices, testing strategies, and use of Oracle's built-in tools for data validation. 9 | 7. **Oracle Editions and Database Types**: Mention the specific Oracle database editions you've worked with (e.g., Standard, Enterprise) and any specialized database types (e.g., Oracle NoSQL, Oracle Autonomous Database). 10 | 8. **Oracle Terminology**: List key Oracle terms you're familiar with, such as instance, schema, tablespaces, or any specific features or tools you've used. 11 | 9. **Developing Oracle Skills**: Share how you've grown your Oracle skill set through on-the-job experience, formal education, self-study, or training courses. 12 | 10. **Oracle Training**: Describe any formal Oracle training programs or certifications you've completed. 13 | 11. **Industry Certifications**: List any Oracle or related IT certifications you hold, such as Oracle Certified Professional (OCP), Oracle Certified Associate (OCA), etc. 14 | 12. **Resolving Conflicts**: Explain your approach to resolving conflicts by providing an example of a past conflict and how you addressed it. 15 | 13. **Prioritizing Work**: Describe your method for managing and prioritizing tasks, including any tools or strategies you use. 16 | 14. **Education and Career Preparation**: Discuss how your educational background prepared you for working with Oracle technologies or in database management roles. 17 | 15. **Encountering Problems**: Share your approach to problem-solving, including an example of a challenging issue you encountered and how you resolved it. 18 | 16. **Leading a Team**: If applicable, discuss your experience with leadership, focusing on how you led a team, managed projects, or mentored colleagues in Oracle technologies. 19 | 17. **Maintaining and Improving Oracle Skills**: Talk about continuous learning practices, such as following Oracle updates, participating in forums, or attending workshops. 20 | 21 | ### In-depth Questions 22 | 23 | 1. **Data Manipulation Language (DML)**: Used for inserting, updating, deleting, and querying data in databases. 24 | 2. **Database Writer Process (DBWn)**: A background process that writes modified blocks from the database buffer cache to the data files. 25 | 3. **Replacing vs. Recreating Procedures**: Replacing preserves privileges and dependencies, while recreating resets them. 26 | 4. **ANALYZE Command**: Used to collect statistics about database objects to help optimize query performance. 27 | 5. **Normal vs. Nested Tables**: Normal tables are structured in rows and columns, while nested tables allow storing sets of values in a single column. 28 | 6. **Creating a Database Dictionary**: Involve creating and populating system tables that store metadata about the database. 29 | 7. **Database Maintenance**: Discuss routine tasks such as performance tuning, backup and recovery, and updating statistics. 30 | 8. **Storing Values in Binary Format**: Mention using BLOB (Binary Large Object) data types for storing binary data. 31 | 9. **Coding Languages with Oracle**: PL/SQL is the primary programming language, but also mention any others you've used, such as Java or Python. 32 | 10. **Data Types for Specific Memory Sizes**: Discuss choosing data types based on precision needs and memory optimization, such as VARCHAR2, NUMBER, or BLOB. 33 | 11. **Evaluating Sub-queries**: Discuss how to use different types of sub-queries (correlated, non-correlated) and their impact on query performance. 34 | 12. **Explaining Oracle to a Non-expert**: Simplify Oracle's role as a database management system that allows storing, retrieving, and manipulating data. 35 | 13. **Important Functions of Oracle**: Highlight critical functionalities, such as transaction management, data security, and scalability. 36 | 14. **Improving Oracle's Processes**: Share your thoughts on potential improvements, focusing on areas like user experience, performance, or cloud integration. 37 | 15. **Training in Oracle**: Describe your experience with training others, focusing on methods used to convey complex Oracle concepts effectively. 38 | -------------------------------------------------------------------------------- /Concept_Guide/software-architecture.md: -------------------------------------------------------------------------------- 1 | Sources: 2 | https://business.linkedin.com/talent-solutions/resources/how-to-hire-guides/software-architect/interview-questions 3 | 4 | ## Fundamentals 5 | 6 | ### Key Software Architecture Principles 7 | 8 | Solid architecture is built upon key principles: 9 | 10 | - **Modularity:** Divide your system into manageable components for easier maintenance. 11 | - **Separation of Concerns:** Isolate different aspects (e.g., UI, business logic) to enhance reusability and maintainability. 12 | - **Abstraction:** Hide complex implementation details behind simple interfaces. 13 | - **Encapsulation:** Restrict access to internal components, reducing unintended interactions. 14 | 15 | 16 | 17 | ### Design Patterns and Best Practices 18 | 19 | Design patterns are reusable solutions to common design problems. Familiarize yourself with patterns like: 20 | 21 | - **Singleton:** Ensures a class has only one instance and provides a global point of access. 22 | - **Factory Method:** Defines an interface for creating objects but lets subclasses decide which class to instantiate. 23 | - **Observer:** Establishes a dependency between objects so that when one changes state, others are notified and updated. 24 | 25 | 26 | 27 | ### SOLID Principles and Their Application 28 | 29 | SOLID principles guide clean and maintainable design: 30 | 31 | - **Single Responsibility Principle (SRP):** Each class/module should have only one reason to change. 32 | - **Open/Closed Principle (OCP):** Software entities should be open for extension but closed for modification. 33 | - **Liskov Substitution Principle (LSP):** Subtypes must be substitutable for their base types without altering program correctness. 34 | - **Interface Segregation Principle (ISP):** Clients should not be forced to depend on interfaces they do not use. 35 | - **Dependency Inversion Principle (DIP):** High-level modules should not depend on low-level modules; both should depend on abstractions. 36 | 37 | 38 | 39 | ### Architectural Styles 40 | 41 | Different projects demand different architectural styles: 42 | 43 | - **Monolithic:** Single codebase and database. Simple to develop but can hinder scalability and maintenance. 44 | - **Microservices:** Divides the application into smaller, independent services that communicate. Offers scalability and isolation but introduces complexity. 45 | - **Service-Oriented Architecture (SOA):** Services communicate over a network, promoting reusability and flexibility. 46 | 47 | 48 | 49 | ### Scalability and Performance Considerations 50 | 51 | Designing for scalability and performance is a must: 52 | 53 | - **Vertical Scaling:** Adding more resources (CPU, RAM) to a single machine. 54 | - **Horizontal Scaling:** Adding more machines to distribute load. 55 | - **Caching:** Storing frequently accessed data in memory for faster retrieval. 56 | - **Load Balancing:** Distributing incoming traffic across multiple servers to prevent overload. 57 | 58 | 59 | 60 | ## System Design & Archiecture for a Software Architect 61 | 62 | ## System Design and Architecture for a Software Architect 63 | 64 | Now that you've got a solid grasp of the foundational principles, let's take a deeper dive into system design and architecture concepts. 65 | 66 | ### High-Level Design Concepts 67 | 68 | At the high-level, your architecture should outline the major components of your system and how they interact. 69 | 70 | #### Architectural Components and Modules 71 | 72 | Break your system into manageable modules: 73 | 74 | - **Presentation Layer:** Handles user interaction and UI components. 75 | - **Business Logic Layer:** Contains the core business rules and processes. 76 | - **Data Access Layer:** Manages data storage and retrieval. 77 | 78 | #### Data Storage and Management 79 | 80 | Choose the right data storage solutions: 81 | 82 | - **Relational Databases:** Suitable for structured data and complex queries. 83 | - **NoSQL Databases:** Ideal for unstructured or semi-structured data and high scalability. 84 | - **Caching:** Use caching mechanisms to reduce database load and improve performance. 85 | 86 | #### Communication Protocols and APIs 87 | 88 | Different components need to communicate effectively: 89 | 90 | - **RESTful APIs:** Enable communication between services through HTTP methods. 91 | - **Message Queues:** Facilitate asynchronous communication between distributed components. 92 | - **WebSocket:** Provides real-time, full-duplex communication between the client and server. 93 | 94 | **What best practices do you apply to designing software and frameworks?** 95 | 96 | - Mention of key principles like simplicity and scalability 97 | - Comprehension of best practices in programming 98 | - Discussion of how to implement these principles in practice 99 | 100 | **What is the CAP theorem and why is it important?** 101 | 102 | - Familiarity with the theorem and its meaning 103 | - Explanation of the implications of the theorem 104 | - Discussion of how CAP forces necessary compromises 105 | 106 | **Why would you want lower application layers not to be aware of higher ones?** 107 | 108 | - Explanation of the importance of modularity in design 109 | - Reference to greater comprehensibility and elegance 110 | - Discussion of specific cases where this principle might apply 111 | 112 | 113 | 114 | ### Low-Level Design Concepts 115 | 116 | Now, let's get into the nitty-gritty of the actual design and interactions of your software components. 117 | 118 | #### Class Diagrams and UML 119 | 120 | Visualize your software's structure and relationships: 121 | 122 | - **Class Diagrams:** Illustrate classes, attributes, methods, and their associations. 123 | - **Sequence Diagrams:** Show interactions between objects over time. 124 | - **Communication Diagrams:** Focus on how objects collaborate to achieve specific tasks. 125 | 126 | #### Designing for Extensibility and Maintainability 127 | 128 | Plan for the future by designing for change: 129 | 130 | - **Dependency Injection:** Promotes loose coupling and allows easier testing and swapping of components. 131 | - **Interfaces and Abstractions:** Create contracts that classes implement, allowing for easier substitutions. 132 | - **Open/Closed Principle:** Ensure new functionality can be added without modifying existing code. 133 | -------------------------------------------------------------------------------- /Concept_Guide/system design guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LuminaScript/CS_Interview_Prep_Guide/ac78e73834d646fd5dbb06db7dd64b4ab8af6811/Concept_Guide/system design guide.pdf -------------------------------------------------------------------------------- /Leetcode/1d-dynamic-programming.md: -------------------------------------------------------------------------------- 1 | - [70. Climbing Stairs](https://leetcode.com/problems/climbing-stairs) 🟢 EASY 🔵 1-d DP 2 | ```cpp 3 | int climbStairs(int n) { 4 | if(n <= 2) return n; 5 | vector dp(n + 1, 1); 6 | dp[2] = 2; 7 | for(int i = 3; i <= n; i++){ 8 | dp[i] = dp[i - 1] + dp[i - 2]; 9 | } 10 | return dp[n]; 11 | } 12 | ``` 13 | - [120. Triangle](https://leetcode.com/problems/triangle/description/) **```🟠MED```** **```Time: O(N^2), Space: O(N)```** 14 | 15 | 16 | ```cpp 17 | int minimumTotal(vector>& triangle) { 18 | int n = triangle.size(); 19 | vector prev(1); 20 | prev[0] = triangle[0][0]; 21 | for(int i = 1; i < n; i++){ 22 | vector cur(i + 1); 23 | for(int j = 0; j <= i; j++){ 24 | if(j > prev.size() - 1) cur[j] = prev[j - 1] + triangle[i][j]; 25 | else if(j == 0) cur[j] = prev[j] + triangle[i][j]; 26 | else cur[j] = min(prev[j], prev[j - 1]) + triangle[i][j]; 27 | } 28 | prev = cur; 29 | } 30 | int minPathSum = INT_MAX; 31 | for(auto n : prev){ 32 | if(n < minPathSum) minPathSum = n; 33 | } 34 | return minPathSum; 35 | } 36 | ``` 37 | - [746. Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) 🟢 EASY 🔵 1-d DP 38 | ```cpp 39 | int minCostClimbingStairs(vector& cost) { 40 | int n = cost.size(); 41 | int dp0 = cost[0], dp1 = cost[1]; 42 | if(n == 2) return min(dp0, dp1); 43 | for(int i = 2; i <= n; i++){ 44 | int temp = min(dp0, dp1); 45 | if(i < n) temp += cost[i]; 46 | dp0 = dp1; 47 | dp1 = temp; 48 | } 49 | return dp1; 50 | } 51 | ``` 52 | - [198. House Robber](https://leetcode.com/problems/house-robber/) 🟠 MEDIUM 🔵 1-d DP 53 | ```cpp 54 | int rob(vector& nums) { 55 | int n = nums.size(); 56 | if(n == 1) return nums[0]; 57 | vector dp(n, 0); 58 | dp[0] = nums[0]; 59 | dp[1] = max(nums[0], nums[1]); 60 | for(int i = 2; i < n; i++){ 61 | dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); 62 | } 63 | return dp[n - 1]; 64 | } 65 | ``` 66 | - [213. House Robber II](https://leetcode.com/problems/house-robber-ii/) 🟠 MEDIUM 🔵 1-d DP 67 | ```cpp 68 | int rob1(vector& nums, int start, int end) { 69 | int n = end - start + 1; 70 | vector dp(n + 1, 0); 71 | dp[0] = nums[start]; 72 | dp[1] = max(nums[start], nums[start + 1]); 73 | for(int i = 2; i < n; i++){ 74 | dp[i] = max(dp[i - 1], dp[i - 2] + nums[start + i]); 75 | } 76 | return dp[n - 1]; 77 | } 78 | int rob(vector& nums) { 79 | int n = nums.size(); 80 | if(n == 1) return nums[0]; 81 | if(n == 2) return max(nums[0], nums[1]); 82 | return max(rob1(nums, 0, n - 2), rob1(nums, 1, n - 1)); 83 | } 84 | ``` 85 | - [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring) 🟠 MEDIUM 🔵 1-d DP 86 | 87 | > Expand from center 88 | 89 | **Time: O(N^2), Space: O(1)** 90 | ```cpp 91 | int expand(string s, int l, int r){ 92 | while(l >= 0 && r < s.size()){ 93 | if(s[l] == s[r]){ 94 | l--, r++; 95 | }else{ 96 | break; 97 | } 98 | } 99 | return r - l + 1 - 2; 100 | } 101 | string longestPalindrome(string s) { 102 | int ans[2] = {0}, dist = 1; 103 | for(int i = 0; i < s.size(); i++){ 104 | int oddLen = expand(s, i, i); 105 | if(oddLen > dist){ 106 | ans[0] = i - oddLen / 2; 107 | ans[1] = i + oddLen / 2; 108 | dist = oddLen; 109 | } 110 | 111 | int evenLen = expand(s, i, i + 1); 112 | if(evenLen > dist){ 113 | ans[0] = i - evenLen / 2 + 1; 114 | ans[1] = i + evenLen / 2; 115 | dist = evenLen; 116 | } 117 | } 118 | return s.substr(ans[0], dist); 119 | } 120 | ``` 121 | 122 | - [647. Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) 🟠 MEDIUM 🔵 1-d DP 123 | 124 | > Expand from center 125 | 126 | **Time: O(N^2), Space: O(1)** 127 | ```cpp 128 | int countSubstrings(string s) { 129 | int cnt = 0, n = s.size(); 130 | for(int i = 0; i < n; i++){ 131 | for(int l = i, r = i; l >= 0 && r < n; l--, r++){ 132 | if(s[l] == s[r]) cnt++; 133 | else break; 134 | } 135 | for(int l = i, r = i + 1; l >= 0 && r < n; l--, r++){ 136 | if(s[l] == s[r]) cnt++; 137 | else break; 138 | } 139 | } 140 | return cnt; 141 | } 142 | ``` 143 | - [740. Delete and Earn](https://leetcode.com/problems/delete-and-earn) **```🟠MED```** 144 | 145 | **1) No Sorting** ```Time: O(N + K), Space: O(N)``` 146 | ```cpp 147 | int deleteAndEarn(vector& nums) { 148 | int maxNum = 0; 149 | unordered_map points; 150 | for(auto n : nums){ 151 | points[n] += n; 152 | maxNum = max(maxNum, n); 153 | } 154 | 155 | int twoBack = 0; // the max num is 0 -> nothing gain 156 | int oneBack = points[1]; // the max num is 1 157 | for(int i = 2; i <= maxNum; i++){ 158 | int temp = oneBack; 159 | oneBack = max(twoBack + points[i], oneBack); 160 | twoBack = temp; 161 | } 162 | return oneBack; 163 | } 164 | ``` 165 | 166 | **2) Sort** ```Time: O(NLogN), Space: O(N)``` 167 | ```cpp 168 | int deleteAndEarn(vector& nums) { 169 | map points; // nums[i], sum; 170 | for(int n : nums) points[n] += n; 171 | 172 | int twoBack = 0; // without prev 173 | int oneBack = points.begin()->second; 174 | 175 | for (auto p = ++points.begin(); p != points.end(); p++){ 176 | int cur = p->first; 177 | int temp = oneBack; 178 | if(points.find(cur - 1) != points.end()){ 179 | oneBack = max(oneBack, twoBack + p->second); 180 | }else{ 181 | oneBack += p->second; 182 | } 183 | twoBack = temp; 184 | } 185 | return oneBack; 186 | } 187 | ``` 188 | -------------------------------------------------------------------------------- /Leetcode/BFS.md: -------------------------------------------------------------------------------- 1 | ## Tree-Based BFS Questions 2 | - [**Leetcode 314: Binary Tree Vertical Order Traversal**](https://leetcode.com/problems/binary-tree-vertical-order-traversal/) 3 | > Given the root of a binary tree, return the vertical order traversal of its nodes' values. 4 | > 5 | > If two nodes are in the same row and column, the order should be from left to right. 6 | 7 | **Solution One: BFS + Sort** 8 | 9 | _Time Complexity: O(NlogN) + Space Complexity: O(N)_ 10 | ```cpp 11 | vector> verticalOrder(TreeNode* root) { 12 | map> verticalMap; 13 | queue> q; 14 | 15 | if (root) { 16 | q.push({root, 0}); 17 | } 18 | 19 | while (!q.empty()) { 20 | TreeNode *cur = q.front().first; 21 | int cur_pos = q.front().second; 22 | q.pop(); 23 | verticalMap[cur_pos].push_back(cur->val); 24 | 25 | if (cur->left) { 26 | q.push({cur->left, cur_pos - 1}); 27 | } 28 | if (cur->right) { 29 | q.push({cur->right, cur_pos + 1}); 30 | } 31 | } 32 | 33 | vector> res; 34 | for (const auto& entry : verticalMap) { 35 | res.push_back(entry.second); 36 | } 37 | return res; 38 | } 39 | ``` 40 | 41 | - [Leetcode 102: Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) 42 | 43 | _Time Complexity: O(N) + Space Comexity: O(N)_ 44 | 45 | ```cpp 46 | vector> levelOrder(TreeNode* root) { 47 | if(!root) return {}; 48 | vector> ans; 49 | queue q; 50 | q.push(root); 51 | while(!q.empty()){ 52 | int n = q.size(); 53 | vector level; 54 | while(n--){ 55 | TreeNode *nd = q.front();q.pop(); 56 | level.push_back(nd->val); 57 | if(nd->left) q.push(nd->left); 58 | if(nd->right) q.push(nd->right); 59 | } 60 | ans.push_back(level); 61 | } 62 | return ans; 63 | } 64 | 65 | ``` 66 | - [Leetcode 103: Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) 67 | > Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between). 68 | 69 | _Time Complexity: O(N) + Space Comexity: O(N)_ 70 | ```cpp 71 | vector> zigzagLevelOrder(TreeNode* root) { 72 | vector> res; 73 | if(!root) return res; 74 | queue q; 75 | q.push(root); 76 | bool leftToRight = true; 77 | 78 | while(!q.empty()){ 79 | int n = q.size(); 80 | vector level(n); 81 | for(int i = 0; i < n; i++){ 82 | TreeNode *node = q.front(); q.pop(); 83 | // fill level array with zigzag order 84 | int index = leftToRight ? i : (n - i - 1); 85 | level[index] = node->val; 86 | 87 | if(node->left) q.push(node->left); 88 | if(node->right) q.push(node->right); 89 | } 90 | leftToRight = !leftToRight; 91 | res.push_back(level); 92 | } 93 | return res; 94 | } 95 | ``` 96 | - [Leetcode 297: Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) (combines BFS and two-pointer approach) 97 | 98 | - [Leetcode 559: Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/) 99 | 100 | Time Complexity: O(N) + Space Complexity: O(N) 101 | ```cpp 102 | int maxDepth(Node* root) { 103 | if (!root) return 0; 104 | stack> stk; 105 | stk.push(make_pair(root, 1)); 106 | int depth = 0; 107 | while(!stk.empty()){ 108 | auto cur = stk.top(); stk.pop(); 109 | root = cur.first; 110 | int cur_dep = cur.second; 111 | if(root){ 112 | depth = std::max(depth, cur_dep); 113 | for(auto c : root->children){ 114 | stk.push({c, cur_dep + 1}); 115 | } 116 | 117 | } 118 | } 119 | return depth; 120 | } 121 | ``` 122 | 123 | ### Graph-Based BFS Questions 124 | - [Leetcode 200: Number of Islands](https://leetcode.com/problems/number-of-islands/) 125 | 126 | Time Complexity : O(N * M) + Space Complexity : O(min(N, M)) 127 | 128 | ```cpp 129 | int numIslands(vector>& grid) { 130 | int nr = grid.size(); 131 | if(!nr) return 0; 132 | int nc = grid[0].size(); 133 | int num_islands = 0; 134 | for(int r = 0; r < nr; r++){ 135 | for(int c = 0; c < nc; c++){ 136 | if(grid[r][c] == '1'){ 137 | num_islands++; 138 | grid[r][c] = '0'; 139 | queue> nbs; // neighbors 140 | nbs.push({r, c}); 141 | while(!nbs.empty()){ 142 | auto rc = nbs.front(); nbs.pop(); 143 | int row = rc.first, col = rc.second; 144 | if(row - 1 >= 0 && grid[row - 1][col] == '1'){ // up 145 | grid[row - 1][col] = '0'; 146 | nbs.push({row - 1, col}); 147 | } 148 | if(row + 1 < nr && grid[row + 1][col] == '1'){ // down 149 | grid[row + 1][col] = '0'; 150 | nbs.push({row + 1, col}); 151 | } 152 | if(col - 1 >= 0 && grid[row][col - 1] == '1'){ // left 153 | grid[row][col - 1] = '0'; 154 | nbs.push({row, col - 1}); 155 | } 156 | if(col + 1 < nc && grid[row][col + 1] == '1'){ // right 157 | grid[row][col + 1] = '0'; 158 | nbs.push({row, col + 1}); 159 | } 160 | 161 | } 162 | 163 | } 164 | } 165 | } 166 | return num_islands; 167 | } 168 | ``` 169 | - [Leetcode 133: Clone Graph](https://leetcode.com/problems/clone-graph/) 170 | 171 | Time Complexity: O(N + M) + Space Complexity: O(N) 172 | 173 | * _Space Complexity: This space is occupied by the visited hash map and in addition to that, space would also be occupied by the recursion stack since we are adopting a recursive approach here. The space occupied by the queue would be equal to O(H) where HHH is the height of the graph. Overall, the space complexity would be O(N)_ 174 | 175 | ```cpp 176 | Node* cloneGraph(Node* node) { 177 | if(!node) return NULL; 178 | 179 | map mp; // store the visited node 180 | queue q; // store the to-be copy node in old graph 181 | Node *nd = new Node(node->val); 182 | mp[node->val] = nd; 183 | q.push(node); 184 | 185 | while(!q.empty()){ 186 | Node *old_nd = q.front(); q.pop(); 187 | for(Node* nb : old_nd->neighbors){ 188 | if(mp.find(nb->val) == mp.end()){ // enqueue unvisited neighbors 189 | mp[nb->val] = new Node(nb->val); // make deep copy of neighbors 190 | q.push(nb); 191 | } 192 | mp[old_nd->val]->neighbors.push_back(mp[nb->val]); 193 | } 194 | } 195 | 196 | return mp[node->val]; 197 | } 198 | 199 | ``` 200 | 201 | - [Leetcode 127: Word Ladder](https://leetcode.com/problems/word-ladder/) 202 | 203 | Time Complexity: O(N * M) + Space Complexity: O(N) 204 | 205 | ```cpp 206 | int ladderLength(string beginWord, string endWord, vector& wordList) { 207 | unordered_set notVisited(wordList.begin(), wordList.end()); 208 | 209 | // Early exit 210 | if (notVisited.find(endWord) == notVisited.end()) return 0; 211 | 212 | queue q; 213 | int len = 1; 214 | q.push(beginWord); 215 | 216 | while (!q.empty()) { 217 | int levelSize = q.size(); // number of elements at the current level 218 | for (int i = 0; i < levelSize; i++) { 219 | string word = q.front(); q.pop(); 220 | if (word == endWord) return len; 221 | 222 | // bfs search 223 | for(int j = 0; j < word.size(); j++){ 224 | for(char k = 'a'; k <= 'z'; k++){ 225 | string w = word; 226 | w[j] = k; 227 | if(notVisited.find(w) != notVisited.end()){ 228 | q.push(w); 229 | notVisited.erase(w); 230 | } 231 | } 232 | } 233 | } 234 | len++; // Increment length after processing all nodes at the current level 235 | } 236 | return 0; 237 | } 238 | 239 | ``` 240 | 241 | - [Leetcode 490: The Maze](https://leetcode.com/problems/the-maze/) 242 | 243 | ```cpp 244 | 245 | bool hasPath(vector>& maze, vector& start, vector& destination) 246 | { 247 | int m = maze.size(); 248 | int n = maze[0].size(); 249 | vector> visited(m, vector(n, false)); 250 | vector dirX{0, 1, 0, -1}; 251 | vector dirY{-1, 0, 1, 0}; 252 | 253 | queue> q; 254 | q.push(start); 255 | visited[start[0]][start[1]] = true; 256 | 257 | while(!q.empty()){ 258 | vector cur = q.front(); q.pop(); 259 | if(cur[0] == destination[0] && cur[1] == destination[1]) return true; 260 | 261 | for(int i = 0; i < 4; i++){ 262 | int r = cur[0]; 263 | int c = cur[1]; 264 | while (r >= 0 && r < m && c >= 0 && c < n && maze[r][c] == 0) { 265 | r += dirX[i]; 266 | c += dirY[i]; 267 | } 268 | r -= dirX[i]; 269 | c -= dirY[i]; 270 | if (!visited[r][c]) { 271 | q.push({r, c}); 272 | visited[r][c] = true; 273 | } 274 | } 275 | } 276 | return false; 277 | } 278 | 279 | ``` 280 | - [Leetcode 323: Connected Component in Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/description/) 281 | 282 | Time Complexity: O(N*2) + Space Complexity: O(N + E) 283 | 284 | ```cpp 285 | int countComponents(int n, vector>& edges) { 286 | if (n == 1) return 1; 287 | vector> g(n); // O(E) 288 | for(vector e : edges){ 289 | int par = e[0]; 290 | int chd = e[1]; 291 | g[chd].push_back(par); 292 | g[par].push_back(chd); 293 | } 294 | 295 | unordered_set visited; // O(N) 296 | int cnt = 0; 297 | for(int i = 0; i < n; i++){ // O(N) 298 | if(visited.find(i) == visited.end()){ // new unvisited node = start of a new cc 299 | cnt++; 300 | queue q; // O(N) 301 | q.push(i); 302 | visited.insert(i); 303 | while(!q.empty()){ // O(N) : bfs on unvisited node -> visit all one in this cc 304 | int curr = q.front(); q.pop(); 305 | for(int nb : g[curr]){ 306 | if(visited.find(nb) == visited.end()){ 307 | q.push(nb); 308 | visited.insert(nb); 309 | } 310 | } 311 | } 312 | } 313 | } 314 | return cnt; 315 | } 316 | ``` 317 | 318 | - [Leetcode 130: Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) 319 | 320 | _Solution Source: https://leetcode.com/problems/surrounded-regions/solutions/4408885/bfs-faster-than-97-c_ 321 | 322 | _Time Complexity: O(NM) + Space Complexity: O(NM)_ 323 | 324 | ```cpp 325 | void solve(vector>& board) { 326 | int n=board.size(),m=board[0].size(); 327 | vector> visited(n,vector(m,0)); 328 | vector> dir = {{0,1},{0,-1},{1,0},{-1,0}}; 329 | queue> q; 330 | 331 | for(int i=0;i0 && i0 && j=0 && row=0 && col>& routes, int s, int t) { 371 | if(s == t) return 0; 372 | 373 | unordered_map> adjList; 374 | for(int route = 0; route < routes.size(); route++){ 375 | for(auto stop: routes[route]){ 376 | adjList[stop].push_back(route); 377 | } 378 | } 379 | 380 | queue q; 381 | unordered_set vis; 382 | for(auto route : adjList[s]){ 383 | q.push(route); 384 | vis.insert(route); 385 | } 386 | 387 | int busCnt = 1; 388 | while(!q.empty()){ 389 | int size = q.size(); 390 | for(int i = 0; i < size; i++){ 391 | int route = q.front(); q.pop(); 392 | 393 | for(int stop : routes[route]){ 394 | if(stop == t){ 395 | return busCnt; 396 | } 397 | for(int nextRoute : adjList[stop]){ 398 | if(vis.count(nextRoute) == 0){ 399 | vis.insert(nextRoute); 400 | q.push(nextRoute); 401 | } 402 | } 403 | } 404 | } 405 | busCnt++; 406 | } 407 | return -1; 408 | } 409 | }; 410 | 411 | ``` 412 | 413 | - [Leetcode 1091: Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) 414 | - [Leetcode 542: 01 Matrix](https://leetcode.com/problems/01-matrix/) 415 | - [Leetcode 1293: Shortest Path in a Grid with Obstacles Elimination](https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/) 416 | - [Leetcode 417: Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) 417 | 418 | ### Topological Sorting Questions 419 | - [Leetcode 207: Course Schedule (I, II)](https://leetcode.com/problems/course-schedule/) 420 | 421 | Time Complexity : O(M + N) + Space Complexity : O(M + N) 422 | 423 | ```cpp 424 | bool canFinish(int numCourses, vector>& prerequisites) { 425 | vector indegree(numCourses); 426 | vector> adj(numCourses); 427 | for(auto preq : prerequisites){ 428 | adj[preq[1]].push_back(preq[0]); 429 | indegree[preq[0]]++; 430 | } 431 | 432 | queue q; 433 | for(int i = 0; i < numCourses; i++){ 434 | if(indegree[i] == 0) q.push(i); 435 | } 436 | 437 | int nodesVisited = 0; 438 | while(!q.empty()){ 439 | int node = q.front(); q.pop(); 440 | nodesVisited++; 441 | 442 | for(int nbs : adj[node]){ 443 | if(--indegree[nbs] == 0) q.push(nbs); 444 | } 445 | } 446 | return nodesVisited == numCourses; 447 | } 448 | 449 | ``` 450 | 451 | - [Leetcode 444: Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/) 452 | - [Leetcode 269: Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) 453 | - [Leetcode 310: Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) 454 | 455 | Time Complexity: O(|V|) + Space Complexity: O(|V|) 456 | 457 | ```cpp 458 | vector findMinHeightTrees(int n, vector>& edges) { 459 | if(n == 1) return {0}; 460 | vector> graph(n); 461 | vector indegree(n, 0), ans; //vector indegree keeps count of the number of nodes approaching a node 462 | 463 | for(auto &e : edges){ //Creating an adjacency matrix for the given graph 464 | graph[e[0]].push_back(e[1]); 465 | graph[e[1]].push_back(e[0]); 466 | indegree[e[0]]++; 467 | indegree[e[1]]++; 468 | } 469 | 470 | queue q; 471 | for(int i=0; i, greater> q; 8 | int k; 9 | KthLargest(int k, vector& nums) { 10 | this->k = k; 11 | for(auto n : nums) add(n); 12 | } 13 | 14 | int add(int val) { 15 | q.push(val); 16 | if(q.size() > k) q.pop(); 17 | return q.top(); 18 | } 19 | ``` 20 | - [1046. Last Stone Weight](https://leetcode.com/problems/last-stone-weight/) 🟢 EASY 🔵 Max Heap 21 | 22 | Each time around the main loop, there is a net loss of either 1 or 2 stones. Thus ```N - 1``` Maximum Itererations. 23 | 24 | **Time : ```O(NlogN)``` | Space : ```O(N)```** 25 | ```cpp 26 | int lastStoneWeight(vector& stones) { 27 | priority_queue maxheap; 28 | for(int n : stones) maxheap.push(n); 29 | while(maxheap.size() > 1){ 30 | int x = maxheap.top(); maxheap.pop(); 31 | int y = maxheap.top(); maxheap.pop(); 32 | if(x < y) maxheap.push(y - x); 33 | else if(x > y) maxheap.push(x - y); 34 | } 35 | return maxheap.empty() ? 0 : maxheap.top(); 36 | } 37 | ``` 38 | - [973. K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) 🟠 MEDIUM 🔵 Min Heap 🔵 Hash Map 39 | ```cpp 40 | vector> kClosest(vector>& points, int k) { 41 | priority_queue> pq; 42 | 43 | for(int i = 0; i < points.size(); ++i) { 44 | double distance = sqrt(pow(points[i][0], 2) + pow(points[i][1], 2)); 45 | pq.push({-distance, i}); 46 | } 47 | 48 | vector> res; 49 | while(k-- > 0 && !pq.empty()) { 50 | auto [dist, idx] = pq.top(); pq.pop(); 51 | res.push_back(points[idx]); 52 | } 53 | 54 | return res; 55 | } 56 | ``` 57 | - [215. Kth Largest Element In An Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) 🟠 MEDIUM 🔵 Max Heap 58 | 59 | **Time : ```O(nlogk)``` | Space : ```O(k)```** 60 | ```cpp 61 | int findKthLargest(vector& nums, int k) { 62 | priority_queue pq; 63 | for(int n : nums){ 64 | pq.push(-n); 65 | if(pq.size() > k) pq.pop(); 66 | } 67 | return -pq.top(); 68 | } 69 | ``` 70 | - [621. Task Scheduler](https://leetcode.com/problems/task-scheduler/) 🟠 MEDIUM 🔵 Max Heap 🔵 Hash Map 71 | 72 | **Time : ```O(nlogk)``` | Space : ```O(n)```** k is the # of task type 73 | ```cpp 74 | int leastInterval(vector& tasks, int n) { 75 | if(n == 0) return tasks.size(); 76 | 77 | unordered_map mp; 78 | for(char c : tasks) mp[c]++; 79 | 80 | priority_queue> pq; 81 | for(auto p : mp) pq.push({p.second, p.first}); 82 | 83 | int alltime = 0, cycle = n + 1; 84 | vector seq; 85 | while(!pq.empty()){ 86 | int time = 0; 87 | vector> tmp; 88 | for(int i = 0; i < cycle; i++){ 89 | if(!pq.empty()){ 90 | tmp.push_back(pq.top()); 91 | pq.pop(); 92 | time++; 93 | } 94 | } 95 | for(auto t : tmp){ 96 | if(--t.first) pq.push(t); 97 | } 98 | alltime += !pq.empty() ? cycle : time; 99 | } 100 | return alltime; 101 | } 102 | ``` 103 | - [Design Twitter](https://leetcode.com/problems/design-twitter/) 🟠 MEDIUM 🔵 Max Heap 🔵 Hash Map 104 | ```cpp 105 | priority_queue>> pq; 106 | int time = 0; 107 | unordered_map> mp; 108 | Twitter() { } 109 | 110 | void postTweet(int userId, int tweetId) { 111 | pq.push({++time, {tweetId, userId}}); 112 | } 113 | 114 | vector getNewsFeed(int userId) { 115 | vector tweetIds; 116 | vector>> temp; 117 | auto followees = mp[userId]; 118 | int cnt = 0; 119 | while(cnt < 10 && !pq.empty()){ 120 | auto p = pq.top(); pq.pop(); 121 | int followeeId = p.second.second; 122 | if(userId == followeeId || followees.find(followeeId) != followees.end()){ 123 | tweetIds.push_back(p.second.first); 124 | cnt++; 125 | } 126 | temp.push_back(p); 127 | } 128 | for(auto t : temp) pq.push(t); 129 | return tweetIds; 130 | } 131 | 132 | void follow(int followerId, int followeeId) { 133 | mp[followerId].insert(followeeId); 134 | } 135 | 136 | void unfollow(int followerId, int followeeId) { 137 | mp[followerId].erase(followeeId); 138 | } 139 | ``` 140 | - [Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/) 141 | - [Maximum Subsequence Score](https://leetcode.com/problems/maximum-subsequence-score/) 142 | - [Single Threaded Cpu](https://leetcode.com/problems/single-threaded-cpu/) 143 | - [Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) 144 | - [Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) 145 | - [Find The Kth Largest Integer In The Array](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) 146 | - [Reorganize String](https://leetcode.com/problems/reorganize-string/) 147 | - [Longest Happy String](https://leetcode.com/problems/longest-happy-string/) 148 | - [Car Pooling](https://leetcode.com/problems/car-pooling/) 149 | - [Find Median From Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) 🟠 MEDIUM 🔵 Max Heap 🔵 Min Heap 150 | ```cpp 151 | priority_queue lo; // max heap leep frist half 152 | priority_queue, greater> hi; // min heap keep second half 153 | void addNum(int num) { 154 | lo.push(num); 155 | hi.push(lo.top()); lo.pop(); 156 | if(lo.size() < hi.size()){ 157 | lo.push(hi.top()); hi.pop(); 158 | } 159 | } 160 | double findMedian() { 161 | if(lo.size() > hi.size()) 162 | return lo.top(); 163 | return ((double) lo.top() + hi.top()) * 0.5; 164 | } 165 | ``` 166 | - [Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/) 167 | - [IPO](https://leetcode.com/problems/ipo/) 168 | -------------------------------------------------------------------------------- /Leetcode/backtrack.md: -------------------------------------------------------------------------------- 1 | - [51. N-Queens](https://leetcode.com/problems/n-queens/) 🔴 HARD 🔵 Backtrack 2 | 3 | **Time: ```O(N!)```, Space: ```O(N^2)```** 4 | ```cpp 5 | vector> sols; 6 | vector> solveNQueens(int n) { 7 | vector board(n, string(n, '.')); // Initialize the board with '.' 8 | set columns; // Tracks columns where queens are placed. 9 | set diag1; // Tracks \ diagonals where queens are placed. 10 | set diag2; // Tracks / diagonals where queens are placed. 11 | 12 | backtrack(0, n, board, columns, diag1, diag2); 13 | return sols; 14 | } 15 | 16 | void backtrack(int row, int n, vector& board, set& columns, set& diag1, set& diag2) { 17 | if (row == n) { 18 | sols.push_back(board); // Found a solution. 19 | return; 20 | } 21 | 22 | for (int col = 0; col < n; ++col) { 23 | if (columns.count(col) || diag1.count(row - col) || diag2.count(row + col)) continue; // Check if the queen placement is safe. 24 | 25 | // Place the queen. 26 | board[row][col] = 'Q'; 27 | columns.insert(col); 28 | diag1.insert(row - col); 29 | diag2.insert(row + col); 30 | 31 | // Move to the next row. 32 | backtrack(row + 1, n, board, columns, diag1, diag2); 33 | 34 | // Remove the queen (backtrack). 35 | board[row][col] = '.'; 36 | columns.erase(col); 37 | diag1.erase(row - col); 38 | diag2.erase(row + col); 39 | } 40 | } 41 | ``` 42 | - [52. N-Queens](https://leetcode.com/problems/n-queens-ii/) 🔴 HARD 🔵 Backtrack 43 | 44 | **Time: ```O(N!)```, Space: ```O(N^2)```** 45 | ```cpp 46 | int sols = 0; 47 | void backtrack(int row, int n, set& columns, set& diag1, set& diag2) { 48 | if (row == n) { 49 | sols++; 50 | return; 51 | } 52 | 53 | for (int col = 0; col < n; ++col) { 54 | if (columns.count(col) || diag1.count(row - col) || diag2.count(row + col)) continue; // Check if the queen placement is safe. 55 | 56 | columns.insert(col); 57 | diag1.insert(row - col); 58 | diag2.insert(row + col); 59 | 60 | backtrack(row + 1, n, columns, diag1, diag2); 61 | 62 | columns.erase(col); 63 | diag1.erase(row - col); 64 | diag2.erase(row + col); 65 | } 66 | } 67 | int totalNQueens(int n) { 68 | set columns; 69 | set diag1; 70 | set diag2; 71 | 72 | backtrack(0, n, columns, diag1, diag2); 73 | return sols; 74 | } 75 | ``` 76 | - [698. Partition to K Equal Sums Subset](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) 🟠 MEDIUM 🔵 Backtrack 77 | ```cpp 78 | vector nums; 79 | set full; 80 | bool backtrack(int subSum, int k, int i, vector& subsets){ 81 | if(i == nums.size()){ 82 | for(auto n : subsets) 83 | if(subSum != n) return false; 84 | return true; 85 | } 86 | for(int set = 0; set < k; set++){ 87 | if(subsets[set] + nums[i] <= subSum){ 88 | subsets[set] += nums[i]; 89 | if(backtrack(subSum, k, i + 1, subsets)) return true; 90 | subsets[set] -= nums[i]; 91 | if (subsets[set] == 0 || subsets[set] + nums[i] == subSum) break; 92 | } 93 | } 94 | return false; 95 | } 96 | bool canPartitionKSubsets(vector& nums, int k) { 97 | int sum = 0; 98 | for(auto n : nums) sum += n; 99 | 100 | if(sum % k != 0) return false; 101 | int subSum = sum / k; 102 | this->nums = nums; 103 | 104 | vector subsets(k, 0); 105 | return backtrack(subSum, k, 0, subsets); 106 | } 107 | ``` 108 | 109 | - [1239. Maximum Length of a Concatenated String with Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) 🟠 MEDIUM 🔵 Backtrack 110 | 111 | Time: O(2^N) [N: the length of arr, 2^N possible combinations of strings in the worst case] 112 | 113 | Space: ```O(N)``` [Max Depths of recursion stacks is N] 114 | 115 | ```cpp 116 | int backtrack(vector& arr, int i, string& mask){ 117 | if(i >= arr.size()) return 0; 118 | string prevmask = mask; 119 | bool isValid = true; 120 | for(auto c : arr[i]){ 121 | if(mask[c - 'a'] == '*'){ 122 | isValid = false; 123 | break; 124 | } 125 | mask[c - 'a'] = '*'; 126 | } 127 | 128 | int excludeCur = backtrack(arr, i + 1, prevmask); 129 | int includeCur = isValid ? arr[i].size() + backtrack(arr, i + 1, mask) : excludeCur; 130 | 131 | return std::max(excludeCur, includeCur); 132 | } 133 | int maxLength(vector& arr) { 134 | string mask = "abcdefghijklmnopqrstuvwxyz"; 135 | return backtrack(arr, 0, mask); 136 | } 137 | ``` 138 | -------------------------------------------------------------------------------- /Leetcode/binary-search.md: -------------------------------------------------------------------------------- 1 | # Basic Knowledge 2 | 3 | Binary search is a fundamental technique with a time complexity of O(logN). Common binary search problems can be categorized into explicit and implicit types. 4 | 5 | ## Explicit Binary Search: 6 | 7 | - [Leetcode 34. Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) 8 | ```cpp 9 | int findBound(vector& nums, int target, bool isLower){ 10 | int n = nums.size(); 11 | int left = 0, right = n - 1; 12 | while(left <= right){ 13 | int mid = left + (right - left) / 2; 14 | int mid_val = nums[mid]; 15 | if(mid_val == target){ 16 | if(isLower){ 17 | if(mid == 0 || (mid - 1 >= 0 && nums[mid - 1] < target)){ 18 | return mid; 19 | }else{ 20 | right = mid - 1; 21 | } 22 | }else{ 23 | if(mid == n - 1 || (mid + 1 < n && nums[mid + 1] > target)){ 24 | return mid; 25 | }else{ 26 | left = mid + 1; 27 | } 28 | } 29 | } 30 | else if(mid_val < target){ 31 | left = mid + 1; 32 | }else{ 33 | right = mid - 1; 34 | } 35 | } 36 | return -1; 37 | } 38 | 39 | vector searchRange(vector& nums, int target) { 40 | vector res(2, -1); 41 | int n = nums.size(); 42 | if(n == 0) return res; 43 | res[0] = findBound(nums, target, true); 44 | res[1] = findBound(nums, target, false); 45 | return res; 46 | } 47 | ``` 48 | - [Leetcode 33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) 49 | ```cpp 50 | int search(vector& nums, int target) { 51 | int left = 0, right = nums.size() - 1; 52 | while(left <= right){ 53 | int mid = left + (right - left) / 2; 54 | if(nums[mid] == target) return mid; 55 | if(nums[left] <= nums[mid]){ // left is sorted 56 | if(target < nums[mid] && target >= nums[left]) 57 | right = mid - 1; 58 | else 59 | left = mid + 1; 60 | }else{ // right is sorted 61 | if (target > nums[mid] && target <= nums[right]) 62 | left = mid + 1; 63 | else 64 | right = mid -1 ; 65 | } 66 | } 67 | return -1; 68 | } 69 | ``` 70 | - [Leetcode 1095. Find in Mountain Array](https://leetcode.com/problems/find-in-mountain-array/) 71 | ```cpp 72 | int findInMountainArray(int target, MountainArray &mountainArr) { 73 | int peak = findPeak(mountainArr); 74 | int index = binarySearchAsc(mountainArr, 0, peak, target); 75 | if (index != -1) { 76 | return index; 77 | } 78 | return binarySearchDesc(mountainArr, peak + 1, mountainArr.length() - 1, target); 79 | } 80 | 81 | int findPeak(MountainArray &mountainArr) { 82 | int left = 0, right = mountainArr.length() - 1; 83 | while (left < right) { 84 | int mid = left + (right - left) / 2; 85 | if (mountainArr.get(mid) < mountainArr.get(mid + 1)) { 86 | // Ascending part 87 | left = mid + 1; 88 | } else { 89 | // Descending part 90 | right = mid; 91 | } 92 | } 93 | return left; 94 | } 95 | 96 | int binarySearchAsc(MountainArray &mountainArr, int left, int right, int target) { 97 | while (left <= right) { 98 | int mid = left + (right - left) / 2; 99 | int midVal = mountainArr.get(mid); 100 | if (midVal == target) { 101 | return mid; 102 | } else if (midVal < target) { 103 | left = mid + 1; 104 | } else { 105 | right = mid - 1; 106 | } 107 | } 108 | return -1; 109 | } 110 | 111 | int binarySearchDesc(MountainArray &mountainArr, int left, int right, int target) { 112 | while (left <= right) { 113 | int mid = left + (right - left) / 2; 114 | int midVal = mountainArr.get(mid); 115 | if (midVal == target) { 116 | return mid; 117 | } else if (midVal > target) { 118 | left = mid + 1; 119 | } else { 120 | right = mid - 1; 121 | } 122 | } 123 | return -1; 124 | } 125 | 126 | ``` 127 | - [Leetcode 162. Find Peak Element](https://leetcode.com/problems/find-peak-element/) 128 | 129 | **Solution 1(Smartest)** 130 | ```cpp 131 | int findPeakElement(vector& nums) { 132 | int n = nums.size(); 133 | int left = 0, right = n - 1; 134 | while(left < right){ 135 | int mid = left + (right - left) / 2; 136 | if(nums[mid] < nums[mid + 1]) left = mid + 1; 137 | else right = mid; 138 | } 139 | return left; 140 | } 141 | ``` 142 | 143 | **Solution 2** 144 | ```cpp 145 | int findPeakElement(vector& nums) { 146 | int n = nums.size(); 147 | int left = 0, right = n - 1; 148 | while(left < right){ 149 | int mid = left + (right - left) / 2; 150 | int mid_val = nums[mid]; 151 | if((mid == 0 || mid_val >= nums[mid - 1]) && (mid >= n - 1 || (mid_val >= nums[mid + 1]))){ 152 | return mid; 153 | } 154 | if(mid == 0 || mid == n - 1){ 155 | mid == 0 ? left = 1 : right = n - 2; 156 | continue; 157 | } 158 | 159 | else if(mid_val <= nums[mid - 1]){ 160 | right = mid - 1; 161 | }else{ 162 | left = mid + 1; 163 | } 164 | } 165 | return left; 166 | } 167 | ``` 168 | 169 | 170 | - [Leetcode 278. First Bad Version](https://leetcode.com/problems/first-bad-version/) 171 | ```cpp 172 | int firstBadVersion(int n) { 173 | int left = 1, right = n; 174 | while(left <= right){ 175 | int mid = left + (right - left) / 2; 176 | if(!isBadVersion(mid)) left = mid + 1; 177 | else right = mid - 1; 178 | } 179 | return left; 180 | } 181 | ``` 182 | - [Leetcode 74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) 183 | ```cpp 184 | bool searchMatrix(vector>& matrix, int target) { 185 | if (matrix.empty() || matrix[0].empty()) return false; 186 | 187 | int row = 0; 188 | int col = matrix[0].size() - 1; 189 | 190 | while (row < matrix.size() && col >= 0) { 191 | if (matrix[row][col] == target) { 192 | return true; 193 | } else if (matrix[row][col] > target) { 194 | // Move left 195 | col--; 196 | } else { 197 | // Move down 198 | row++; 199 | } 200 | } 201 | 202 | return false; 203 | } 204 | 205 | ``` 206 | - [Leetcode 240. Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) 207 | ```cpp 208 | bool searchMatrix(vector>& matrix, int target) { 209 | if (matrix.empty() || matrix[0].empty()) return false; 210 | 211 | int row = 0; 212 | int col = matrix[0].size() - 1; 213 | 214 | while (row < matrix.size() && col >= 0) { 215 | if (matrix[row][col] == target) return true; 216 | else if (matrix[row][col] > target) col--; 217 | else row++; 218 | } 219 | 220 | return false; 221 | } 222 | ``` 223 | 224 | ## Implicit Binary Search: 225 | 226 | - [Leetcode 69. Sqrt(x)](https://leetcode.com/problems/sqrtx/) 227 | ```cpp 228 | int mySqrt(int x) { 229 | if(x < 2) return x; 230 | int left = 2, right = x / 2; 231 | while(left <= right){ 232 | int mid = (left + right) / 2; 233 | long y = (long)mid * mid; 234 | if(y < x) left = mid + 1; 235 | else if( y > x) right = mid - 1; 236 | else return mid; 237 | } 238 | return right; 239 | } 240 | ``` 241 | - [Leetcode 540. Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) 242 | ```cpp 243 | int singleNonDuplicate(vector& nums) { 244 | int left = 0, right = nums.size() - 1; 245 | while(left < right){ 246 | int mid = (left + right) / 2; 247 | if(mid % 2 == 1) mid--; 248 | if(nums[mid] != nums[mid+1]) right = mid; 249 | else left = mid + 2; 250 | } 251 | return nums[left]; 252 | 253 | } 254 | ``` 255 | - [Leetcode 644. Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/) 256 | 257 | Detailed Solution Explanation: https://leetcode.com/problems/maximum-average-subarray-ii/solutions/4732642/c-bs-great-detailed-explanation 258 | 259 | ```cpp 260 | bool check(vector& nums, double mid, int k){ 261 | double sum = 0, prev = 0, min_sum = 0; 262 | for(int i = 0; i < k; i++){ 263 | sum += nums[i] - mid; 264 | } 265 | if(sum >= 0) return true; 266 | for(int i = k; i < nums.size(); i++){ 267 | sum += nums[i] - mid; 268 | prev += nums[i - k] - mid; 269 | min_sum = min(prev, min_sum); 270 | if(sum >= min_sum) return true; 271 | } 272 | return false; 273 | } 274 | double findMaxAverage(vector& nums, int k) { 275 | double max_val = INT_MIN, min_val = INT_MAX; 276 | for(auto n : nums){ 277 | max_val = max_val > n ? max_val : n; 278 | min_val = min_val < n ? min_val : n; 279 | } 280 | double prev_mid = max_val, error = INT_MAX; 281 | while(error > 0.00001){ 282 | double mid = (max_val + min_val) * 0.5; 283 | if(check(nums, mid, k)) min_val = mid; 284 | else max_val = mid; 285 | error = abs(prev_mid - mid); 286 | prev_mid = mid; 287 | } 288 | return min_val; 289 | } 290 | ``` 291 | - [Leetcode 528. Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight/) 292 | - [Leetcode 1300. Sum of Mutated Array Closest to Target](https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/) 293 | - [Leetcode 1060. Missing Element in Sorted Array](https://leetcode.com/problems/missing-element-in-sorted-array/) 294 | - [Leetcode 1062. Longest Repeating Substring](https://leetcode.com/problems/longest-repeating-substring/) 295 | - [Leetcode 1891. Cutting Ribbons](https://leetcode.com/problems/cutting-ribbons/) 296 | - [Leetcode 410. Split Array Largest Sum (similar to 1891)](https://leetcode.com/problems/split-array-largest-sum/) 297 | -------------------------------------------------------------------------------- /Leetcode/bit-operation.md: -------------------------------------------------------------------------------- 1 | - [67. Add Binary](https://leetcode.com/problems/add-binary/) 2 | ```cpp 3 | string addBinary(string a, string b) { 4 | string res; 5 | int i = a.length() - 1; 6 | int j = b.length() - 1; 7 | int carry = 0; 8 | while(i >= 0 || j >= 0){ 9 | int sum = carry; 10 | if(i >= 0) sum += a[i--] - '0'; 11 | if(j >= 0) sum += b[j--] - '0'; 12 | carry = sum > 1 ? 1 : 0; 13 | res += to_string(sum % 2); 14 | } 15 | if(carry) res += to_string(carry); 16 | reverse(res.begin(), res.end()); 17 | return res; 18 | } 19 | ``` 20 | - [136. Single Number](https://leetcode.com/problems/single-number) Medium 21 | ```c 22 | int singleNumber(int* nums, int numsSize) { 23 | uint32_t loner = 0; 24 | for(int i = 0; i <= 31; i++){ 25 | uint32_t bitSum = 0; 26 | for(int j = 0; j < numsSize; j++){ 27 | bitSum += (nums[j] >> i) & 1; 28 | } 29 | loner |= (bitSum % 2) << i; 30 | } 31 | return loner; 32 | } 33 | ``` 34 | 35 | - [137. Single Number II](https://leetcode.com/problems/single-number-ii) Medium 36 | ```c 37 | int singleNumber(int* nums, int numsSize) { 38 | uint32_t loner = 0; 39 | for(int i = 0; i < 32; i++) { 40 | uint32_t bitSum = 0; 41 | for(int j = 0; j < numsSize; j++) { 42 | bitSum += (nums[j] >> i) & 1; 43 | } 44 | loner |= (bitSum % 3) << i; 45 | } 46 | return loner; 47 | } 48 | ``` 49 | 50 | - [190. Reverse Bits](https://leetcode.com/problems/reverse-bits) Easy 51 | ```c 52 | uint32_t reverseBits(uint32_t n) { 53 | uint32_t rev = 0; 54 | for(int i = 31; i >= 0; i--){ 55 | uint32_t lsb = n >> i & 0x1; 56 | rev |= lsb << (31 - i); 57 | n >> 1; 58 | } 59 | return rev; 60 | } 61 | ``` 62 | 63 | - [191. Numbers of 1 Bits](https://leetcode.com/problems/number-of-1-bits) Easy 64 | ```c 65 | int hammingWeight(uint32_t n) { 66 | int oneCnt = 0; 67 | for(int i = 0; i <= 31; i++){ 68 | if((n >> i) & 1) oneCnt++; 69 | } 70 | return oneCnt; 71 | } 72 | ``` 73 | 74 | - [201. Bitwise And Of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range) Medium 75 | ```c 76 | int rangeBitwiseAnd(int left, int right) { 77 | int shift = 0; 78 | while(left < right){ 79 | right >>= 1; 80 | left >>= 1; 81 | ++shift; 82 | } 83 | return left << shift; 84 | } 85 | ``` 86 | -------------------------------------------------------------------------------- /Leetcode/greedy.md: -------------------------------------------------------------------------------- 1 | - [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) 🟠 MEDIUM 🔵 Greedy 2 | 3 | Time ```O(N)``` | Space ```O(1)``` 4 | ```cpp 5 | int maxSubArray(vector& nums) { 6 | int cur_res = nums[0]; 7 | int max_res = cur_res; 8 | for(int i = 1; i < nums.size(); i++){ 9 | int n = nums[i]; 10 | cur_res = max(n, cur_res + n); 11 | max_res = max(max_res, cur_res); 12 | } 13 | return max_res; 14 | } 15 | ``` 16 | - [Jump Game](https://leetcode.com/problems/jump-game/) 🟠 MEDIUM 🔵 Greedy 17 | 18 | Time ```O(N)``` | Space ```O(1)``` 19 | ```cpp 20 | bool canJump(vector& nums) { 21 | int furtherestIndex = 0; 22 | for(int i = 0; i < nums.size(); i++){ 23 | if(furtherestIndex >= i) furtherestIndex = max(furtherestIndex, i + nums[i]); 24 | if(furtherestIndex >= nums.size() - 1) return true; 25 | } 26 | return false; 27 | } 28 | ``` 29 | - [Jump Game II](https://leetcode.com/problems/jump-game-ii/) 🟠 MEDIUM 🔵 Greedy 30 | 31 | Time ```O(N)``` | Space ```O(1)``` 32 | ```cpp 33 | int jump(vector& nums) { 34 | if(nums.size() == 1) return 0; 35 | 36 | int curEnd = 0, furthestIdx = 0, jumps = 0; 37 | for(int i = 0; i < nums.size(); i++){ 38 | if(furthestIdx >= i) furthestIdx = max(furthestIdx, i + nums[i]); 39 | if(i == curEnd){ 40 | curEnd = furthestIdx; 41 | jumps++; 42 | if(furthestIdx >= nums.size() - 1) return jumps; 43 | } 44 | } 45 | return jumps; 46 | } 47 | ``` 48 | - [Gas Station](https://leetcode.com/problems/gas-station/) 49 | ```cpp 50 | int canCompleteCircuit(vector& gas, vector& cost) { 51 | int currGain = 0, totalGain = 0, answer = 0; 52 | 53 | for (int i = 0; i < gas.size(); ++i) { 54 | totalGain += gas[i] - cost[i]; 55 | currGain += gas[i] - cost[i]; 56 | if (currGain < 0) { 57 | answer = i + 1; 58 | currGain = 0; 59 | } 60 | } 61 | return totalGain >= 0 ? answer : -1; 62 | } 63 | ``` 64 | - [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) 65 | 66 | ```cpp 67 | bool isNStraightHand(vector& hand, int W) { 68 | map c; 69 | for (int i : hand) c[i]++; 70 | for (auto it : c) 71 | if (c[it.first] > 0) 72 | for (int i = W - 1; i >= 0; --i) 73 | if ((c[it.first + i] -= c[it.first]) < 0) 74 | return false; 75 | return true; 76 | } 77 | ``` 78 | - [1899. Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) 79 | 80 | O(N) + O(1) 81 | ```cpp 82 | bool mergeTriplets(vector>& triplets, vector& t) { 83 | vector res(3); 84 | for(auto s : triplets){ 85 | if(s[0] <= t[0] && s[1] <= t[1] && s[2] <= t[2]) 86 | res = {max(res[0], s[0]), max(res[1], s[1]), max(res[2], s[2])}; 87 | } 88 | return res == t; 89 | } 90 | ``` 91 | - [763. Partition Labels](https://leetcode.com/problems/partition-labels/) 92 | 93 | O(N) + O(1) 94 | ```cpp 95 | vector partitionLabels(string s) { 96 | vector last(26); 97 | for(int i = 0; i < s.size(); i++) last[s[i] - 'a'] = i; 98 | int start = 0, end = 0; 99 | vector res; 100 | for(int i = 0; i < s.size(); i++){ 101 | end = max(end, last[s[i]- 'a']); 102 | if(end == i){ 103 | res.push_back(end - start + 1); 104 | start = i + 1; 105 | } 106 | } 107 | return res; 108 | } 109 | ``` 110 | - [678. Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) 111 | ```cpp 112 | bool checkValidString(string s) { 113 | int minleft = 0, maxleft = 0; 114 | for(auto c : s){ 115 | if(c == '(') minleft++, maxleft++; 116 | else if(c == ')') minleft--, maxleft--; 117 | else minleft--, maxleft++; 118 | if(maxleft < 0) return false; 119 | minleft = max(0, minleft); 120 | } 121 | return minleft == 0; 122 | } 123 | ``` 124 | -------------------------------------------------------------------------------- /Leetcode/hash-map.md: -------------------------------------------------------------------------------- 1 | - [LeetCode 1. Two Sum](https://leetcode.com/problems/two-sum/) **[MED]** 2 | ```cpp 3 | vector twoSum(vector& nums, int target) { 4 | sort(nums.begin(), nums.end()); 5 | int left = 0, right = nums.size() - 1; 6 | while(left < right){ 7 | int sum = nums[left] + nums[right]; 8 | if(sum == target) return {left, right}; 9 | else if(sum > target) right--; 10 | else left++; 11 | } 12 | return {left, right}; 13 | } 14 | ``` 15 | - [LeetCode 409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) **[MED]** 16 | ```cpp 17 | int longestPalindrome(string s) { 18 | unordered_map mp; 19 | int len = 0; 20 | bool foundsingle = false; 21 | 22 | for(auto c : s) mp[c]++; 23 | 24 | for(auto p : mp){ 25 | len += (p.second / 2) * 2; 26 | if(p.second % 2 == 1) foundsingle = true; 27 | } 28 | return foundsingle ? len + 1 : len; 29 | } 30 | ``` 31 | - [LeetCode 146. LRU Cache (Use OrderedDict in Python)](https://leetcode.com/problems/lru-cache/) 32 | - [LeetCode 128. Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) **[MED]** 33 | ```cpp 34 | int longestConsecutive(vector& nums) { 35 | unordered_set st(nums.begin(), nums.end()); 36 | int maxLen = 0; 37 | for(int n : nums){ 38 | if(st.find(n - 1) == st.end()){ 39 | int curLen = 1; 40 | int curN = n; 41 | while(st.find(curN + 1) != st.end()){ 42 | curN++; 43 | curLen++; 44 | } 45 | maxLen = max(maxLen, curLen); 46 | } 47 | } 48 | return maxLen; 49 | } 50 | ``` 51 | - [LeetCode 380. Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) **[MED]** 52 | 53 | > All Operations Must Run in ```O(1)``` 54 | ```cpp 55 | class RandomizedSet { 56 | public: 57 | unordered_map mp; // val -> list index 58 | vector list; 59 | RandomizedSet() {} 60 | 61 | bool insert(int val) { 62 | if(mp.find(val) != mp.end()) return false; 63 | mp[val] = list.size(); 64 | list.push_back(val); 65 | return true; 66 | } 67 | 68 | bool remove(int val) { 69 | if(mp.find(val) == mp.end()) return false; 70 | int lastVal = list[list.size() - 1]; 71 | int curIdx = mp[val]; 72 | list[curIdx] = lastVal; 73 | mp[lastVal] = curIdx; 74 | list.pop_back(); 75 | mp.erase(val); 76 | return true; 77 | } 78 | 79 | int getRandom() { 80 | return list[rand() % list.size()]; 81 | } 82 | }; 83 | 84 | ``` 85 | - [LeetCode 49. Group Anagrams](https://leetcode.com/problems/group-anagrams/) **[MED]** 86 | 87 | **Time Complexity: ```O(NK)``` + Space Complexity : ```O(NK)```** 88 | ```cpp 89 | vector> groupAnagrams(vector& strs) { 90 | unordered_map> mp; 91 | vector> res; 92 | 93 | for(string w : strs) { 94 | vector count(26, 0); 95 | for(char c : w) count[c - 'a']++; 96 | 97 | string key = ""; 98 | for(int i = 0; i < 26; ++i) { 99 | key += string(count[i], 'a' + i); 100 | } 101 | mp[key].push_back(w); 102 | } 103 | 104 | for(auto p : mp) res.push_back(p.second); 105 | 106 | return res; 107 | } 108 | ``` 109 | - [LeetCode 350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) **[EASY]** 110 | 111 | **Time Complexity: ```O(N + M)``` + Space Complexity : ```O(min(N, M))```** 112 | ```cpp 113 | vector intersect(vector& nums1, vector& nums2) { 114 | if (nums1.size() > nums2.size()) return intersect(nums2, nums1); 115 | 116 | unordered_map mp; 117 | for(auto n : nums1) mp[n]++; 118 | 119 | vector res; 120 | for(auto n : nums2){ 121 | if(mp.find(n) != mp.end()){ 122 | res.push_back(n); 123 | mp[n]--; 124 | if(mp[n] == 0) mp.erase(n); 125 | } 126 | } 127 | return res; 128 | } 129 | ``` 130 | - [LeetCode 299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) 131 | - [LeetCode 348. Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) [MED] 132 | ```cpp 133 | class TicTacToe { 134 | public: 135 | vector rows; 136 | vector cols; 137 | int diagonal = 0; 138 | int anti_diagonal = 0; 139 | int n; 140 | TicTacToe(int dim) { 141 | n = dim; 142 | rows = vector(n, 0); 143 | cols = vector(n, 0); 144 | } 145 | 146 | int move(int row, int col, int player) { 147 | int curpt = player == 1 ? 1 : -1; 148 | rows[row] += curpt; 149 | cols[col] += curpt; 150 | if(row == col) diagonal += curpt; 151 | if(n - row - 1== col) anti_diagonal += curpt; 152 | 153 | if(rows[row] == n || cols[col] == n || diagonal == n || anti_diagonal == n) return 1; 154 | else if(rows[row] == -n || cols[col] == -n || diagonal == -n || anti_diagonal == -n) return 2; 155 | else return 0; 156 | } 157 | }; 158 | ``` 159 | 160 | Each link directs you to the problem statement and solution platform on LeetCode, facilitating easy access and practice. 161 | -------------------------------------------------------------------------------- /Leetcode/microsoft-ng.md: -------------------------------------------------------------------------------- 1 | #### Past OA 2 | 3 | ## Handmade Items Processing Time Calculator 4 | 5 | #### Problem Statement 6 | 7 | Given `N` clients who have ordered `N` handmade items, where the `K-th` client ordered exactly one item that takes `T[K]` hours to make. There is only one employee responsible for crafting these items, and their workflow is as follows: 8 | 9 | 1. Spend 1 hour making the first item. 10 | 2. If the item is finished, deliver it. 11 | 3. If the item is NOT finished, place it after ALL REMAINING ITEMS for further work. 12 | 4. The employee then proceeds to the next item in line. 13 | 14 | The challenge is to calculate the total time that clients need to wait for all ordered items to be completed and delivered. 15 | 16 | #### Example 17 | 18 | Consider `T = [3, 1, 2]`, representing the hours needed to make each item for three different clients. 19 | 20 | - The 1st item takes 3 hours to make. 21 | - The 2nd item takes 1 hour. 22 | - The 3rd item takes 2 hours. 23 | 24 | #### Solution 25 | 26 | ```cpp 27 | int timecalc(vector T){ 28 | queue wait; 29 | int total_time = 0; 30 | for(auto t : T) wait.push(t); 31 | while(!q.empty()){ 32 | int cur = q.front(); q.pop(); 33 | cur -= 1; 34 | if(cur > 0) q.push(cur); 35 | total_time++ 36 | } 37 | return total_time; 38 | } 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /Leetcode/microsoft.md: -------------------------------------------------------------------------------- 1 | - [273. Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) - 30.5% Hard 2 | ```cpp 3 | #include 4 | #include 5 | using namespace std; 6 | vector digits = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; 7 | vector tentwenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; 8 | vector tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; 9 | #define one(num) (digits[(num)]) 10 | #define twoLessThan20(num) (tentwenty[(num) - 10]) 11 | #define ten(num) (tens[(num)]) 12 | 13 | class Solution { 14 | public: 15 | string two(int num) { 16 | if (!num) return ""; 17 | else if (num < 10) return one(num); 18 | else if (num < 20) return twoLessThan20(num); 19 | else { 20 | int tenner = num / 10; 21 | int rest = num % 10; 22 | if (rest) return ten(tenner) + " " + one(rest); 23 | else return ten(tenner); 24 | } 25 | } 26 | 27 | string three(int num) { 28 | int hundred = num / 100; 29 | int rest = num % 100; 30 | string res = ""; 31 | if (hundred && rest) res = one(hundred) + " Hundred " + two(rest); 32 | else if (!hundred && rest) res = two(rest); 33 | else if (hundred && !rest) res = one(hundred) + " Hundred"; 34 | return res; 35 | } 36 | 37 | string numberToWords(int num) { 38 | if (num == 0) return "Zero"; 39 | 40 | int billion = num / 1000000000; 41 | int million = (num % 1000000000) / 1000000; 42 | int thousand = (num % 1000000) / 1000; 43 | int remainder = num % 1000; 44 | string result = ""; 45 | 46 | if (billion) result += three(billion) + " Billion"; 47 | if (million) { 48 | if (!result.empty()) result += " "; 49 | result += three(million) + " Million"; 50 | } 51 | if (thousand) { 52 | if (!result.empty()) result += " "; 53 | result += three(thousand) + " Thousand"; 54 | } 55 | if (remainder) { 56 | if (!result.empty()) result += " "; 57 | result += three(remainder); 58 | } 59 | 60 | return result; 61 | } 62 | }; 63 | 64 | ``` 65 | - [146. LRU Cache](https://leetcode.com/problems/lru-cache/) - 42.2% Medium 66 | - [1405. Longest Happy String](https://leetcode.com/problems/longest-happy-string/) - 57.3% Medium 67 | - [1647. Minimum Deletions to Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) - 61.2% Medium 68 | - [1822. Sign of the Product of an Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) - 65.3% Easy 69 | - [138. Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) - 55.5% Medium 70 | - [722. Remove Comments](https://leetcode.com/problems/remove-comments/) - 38.5% Medium 71 | - [545. Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/) - 45.1% Medium 72 | - [1386. Cinema Seat Allocation](https://leetcode.com/problems/cinema-seat-allocation/) - 41.7% Medium 73 | - [200. Number of Islands](https://leetcode.com/problems/number-of-islands/) - 58.5% Medium 74 | - [277. Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) - 47.0% Medium 75 | - [186. Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) - 54.3% Medium 76 | - [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) - 73.2% Medium 77 | - [1239. Maximum Length of a Concatenated String with Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) - 54.1% Medium 78 | - [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) - 48.8% Medium 79 | - [1304. Find N Unique Integers Sum up to Zero](https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/) - 76.3% Easy 80 | - [348. Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) - 57.9% Medium 81 | - [297. Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) - 56.5% Hard 82 | - [253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) - 51.0% Medium 83 | - [165. Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) - 36.7% Medium 84 | - [428. Serialize and Deserialize N-ary Tree](https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/) - 66.7% Hard 85 | - [218. The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) - Hard 86 | -------------------------------------------------------------------------------- /Leetcode/sliding-windows.md: -------------------------------------------------------------------------------- 1 | - [121. Best Time to Buy And Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock) 🟢 EASY 🔵 Sliding Windows 2 | ```cpp 3 | int maxProfit(vector& prices) { 4 | int maxProfit = 0; 5 | for(int r = 0, l = 0; r < prices.size(); r++){ 6 | if(prices[r] > prices[l]) maxProfit = max(maxProfit, prices[r] - prices[l]); 7 | else l = r; 8 | } 9 | return maxProfit; 10 | } 11 | ``` 12 | - [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) 🟢 EASY 🔵 Sliding Windows 🔵 Hash Map 13 | ```cpp 14 | bool containsNearbyDuplicate(vector& nums, int k) { 15 | unordered_map mp; 16 | for(int i = 0; i < nums.size(); i++){ 17 | if(mp.count(nums[i]) && i - mp[nums[i]] <= k) return true; 18 | mp[nums[i]] = i; 19 | } 20 | return false; 21 | } 22 | ``` 23 | - [1314. Number of Subarrays of Size K and Avg Greater than or Equal to Threshold](https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/) 🟠 MEDIUM 🔵 Sliding Windows 24 | ```cpp 25 | int numOfSubarrays(vector& arr, int k, int threshold) { 26 | int curSum = 0, res = 0; 27 | for(int i = 0; i < arr.size(); i++){ 28 | curSum += arr[i]; 29 | if(i < k - 1) continue; 30 | if(i - k >= 0) curSum -= arr[i - k]; 31 | if(curSum / k >= threshold) res++; 32 | } 33 | return res; 34 | } 35 | ``` 36 | - [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters) 🟠 MEDIUM 🔵 Sliding Windows 🔵 Hash Map 37 | ```cpp 38 | int lengthOfLongestSubstring(string s) { 39 | unordered_map mp; 40 | int maxLen = 0; 41 | for(int l = 0, r = 0; r < s.size(); r++){ 42 | if(mp.find(s[r]) != mp.end()){ 43 | while(l <= mp[s[r]]) mp.erase(s[l++]); 44 | } 45 | mp[s[r]] = r; 46 | maxLen = std::max(maxLen, r - l + 1); 47 | } 48 | return maxLen; 49 | } 50 | ``` 51 | - [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement) 52 | - [567. Permutation in String](https://leetcode.com/problems/permutation-in-string) 🟠 MEDIUM 🔵 Sliding Windows 🔵 Hash Map 53 | 54 | **Time ```O(sn)``` + Space ```O(1)```** 55 | ```cpp 56 | bool checkInclusion(string p, string s) { 57 | int pn = p.size(), sn = s.size(); 58 | if(sn < pn) return false; 59 | vector ref(26, 0); 60 | vector windows(26, 0); 61 | for(char c : p) ref[c - 'a']++; 62 | 63 | for(int i = 0; i < sn; i++){ 64 | windows[s[i] - 'a']++; 65 | if(i >= pn) windows[s[i - pn] - 'a']--; 66 | if(ref == windows) return true; 67 | } 68 | return false; 69 | } 70 | ``` 71 | - [Frequency of the Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element) 🟠 MEDIUM 🔵 Sliding Windows 72 | > We only care about the length of sliding windows, but not the content inside it. 73 | > 74 | > Does not shrink the windows, only expand it when we encounter longer valid windows. 75 | 76 | **Time ```O(NlogN)``` + Space ```O(N)```** 77 | ```cpp 78 | int maxFrequency(vector& nums, int k) { 79 | sort(nums.begin(), nums.end()); 80 | int left = 0; 81 | long curr = 0; 82 | 83 | for (int right = 0; right < nums.size(); right++) { 84 | long target = nums[right]; 85 | curr += target; 86 | 87 | if ((right - left + 1) * target - curr > k) { 88 | curr -= nums[left]; 89 | left++; 90 | } 91 | } 92 | 93 | return nums.size() - left; 94 | } 95 | ``` 96 | - [904. Fruits into Baskets](https://leetcode.com/problems/fruit-into-baskets) 🟠 MEDIUM 🔵 Sliding Windows 🔵 Hash Map 97 | 98 | **Solution 1: Adjust Sliding Window's Size** 99 | ```cpp 100 | int totalFruit(vector& fruits) { 101 | unordered_map mp; 102 | int cnt = 0; 103 | int maxFruit = 0, curFruit = 0; 104 | for(int l = 0, r = 0; r < fruits.size(); r++){ 105 | if(mp.find(fruits[r]) == mp.end()) cnt++; 106 | mp[fruits[r]]++; 107 | 108 | curFruit++; 109 | while(cnt > 2){ 110 | if(--mp[fruits[l]] == 0){ 111 | mp.erase(fruits[l]); 112 | cnt--; 113 | } 114 | l++; 115 | curFruit--; 116 | } 117 | maxFruit = std::max(curFruit, maxFruit); 118 | } 119 | return maxFruit; 120 | } 121 | ``` 122 | 123 | **Solution 2: Never Shrinking Sliding Window** 🌟 124 | ```cpp 125 | int totalFruit(vector& fruits) { 126 | unordered_map mp; 127 | int cnt = 0; 128 | int l = 0, r = 0; 129 | while(r < fruits.size()){ 130 | if(mp.find(fruits[r]) == mp.end()) cnt++; 131 | mp[fruits[r]]++; 132 | if(mp.size() > 2){ 133 | if(--mp[fruits[l]] == 0) mp.erase(fruits[l]); 134 | l++; 135 | } 136 | r++; 137 | } 138 | return r - l; 139 | } 140 | ``` 141 | - [1456. Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length) 🟠 MEDIUM 🔵 Sliding Windows 142 | 143 | **Time ```O(N)``` + Space ```O(1)```** 144 | ```cpp 145 | int maxVowels(string s, int k) { 146 | int maxVowel = 0, curVowel = 0; 147 | set vowels= {'a', 'e', 'i', 'o', 'u'}; 148 | for(int l = 0, r = 0; r < s.size(); r++){ 149 | if(vowels.find(s[r]) != vowels.end()) curVowel++; 150 | if(r - l + 1 > k){ 151 | if(vowels.find(s[l]) != vowels.end()) curVowel--; 152 | l++; 153 | } 154 | maxVowel = max(maxVowel, curVowel); 155 | } 156 | return maxVowel; 157 | } 158 | ``` 159 | - [Minimum Number of Flips to Make the Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating) 160 | - [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum) 🟠 MEDIUM 🔵 Sliding Windows 161 | 162 | **Time ```O(N)``` + Space ```O(1)```** 163 | ```cpp 164 | int minSubArrayLen(int target, vector& nums) { 165 | int curSum = 0, minLen = INT_MAX; 166 | for(int l = 0, r = 0; r < nums.size(); r++){ 167 | curSum += nums[r]; 168 | while(curSum - nums[l]>= target) curSum -= nums[l++]; 169 | if(curSum >= target) minLen = min(r - l + 1, minLen); 170 | } 171 | return minLen == INT_MAX ? 0 : minLen; 172 | } 173 | ``` 174 | - [1658. Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero) 🟠 MEDIUM 🔵 Sliding Windows 175 | > Min Operation to Reduce X to Zero <-> Max Length Sub Array for a total sum of ```SUM - X``` 176 | 177 | **Time ```O(N)``` + Space ```O(1)```** 178 | ```cpp 179 | int minOperations(vector& nums, int x) { 180 | int sum = 0; 181 | for(int n : nums) sum += n; 182 | 183 | int maxLen = -1, curSum = 0; 184 | for(int l = 0, r = 0; r < nums.size(); r++){ 185 | curSum += nums[r]; 186 | while(l <= r && curSum > sum - x) curSum -= nums[l++]; 187 | if(curSum == sum - x) maxLen = max(maxLen, r - l + 1); 188 | } 189 | 190 | return maxLen == -1 ? -1 : nums.size() - maxLen; 191 | } 192 | ``` 193 | - [76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring) 🔴 HARD 🔵 Sliding Windows 🔵 Hash Map 194 | 195 | **Time ```O(N + M)``` + Space ```O(1)```** 196 | ```cpp 197 | string minWindow(string s, string t) { 198 | 199 | vector dict(128, 0); 200 | vector windows(128, 0); 201 | vector cnt(128, 0); 202 | for(char c : t) dict[c]++; 203 | 204 | int minLen = INT_MAX; 205 | string minSubstr = ""; 206 | for(int l = 0, r = 0; r < s.size(); r++){ 207 | if(dict[s[r]] > 0) { 208 | cnt[s[r]]++; 209 | if(windows[s[r]] < dict[s[r]]) windows[s[r]]++; 210 | } 211 | if(r - l + 1 > t.size()){ 212 | while(l < r && (dict[s[l]] == 0 || cnt[s[l]] > dict[s[l]])){ 213 | if(cnt[s[l]] > dict[s[l]]) cnt[s[l]]--; 214 | l++; 215 | } 216 | } 217 | 218 | if(dict == windows && r - l + 1 < minLen){ 219 | minLen = r - l + 1; 220 | minSubstr = s.substr(l, r - l + 1); 221 | } 222 | } 223 | return minSubstr; 224 | } 225 | ``` 226 | - [239. Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum) 🔴 HARD 🔵 Sliding Windows 🔵 Monotonue Queue 🔵 Deque 227 | 228 | **Time ```O(N)``` + Space ```O(k)```** 229 | ```cpp 230 | vector maxSlidingWindow(vector& nums, int k) { 231 | deque dq; 232 | vector res; 233 | 234 | for(int i = 0; i < k; i++){ 235 | while(!dq.empty() && nums[i] >= nums[dq.back()]) dq.pop_back(); 236 | dq.push_back(i); 237 | } 238 | 239 | res.push_back(nums[dq.front()]); 240 | for(int i = k; i < nums.size(); i++){ 241 | if(dq.front() == i - k) dq.pop_front(); 242 | while(!dq.empty() && nums[i] >= nums[dq.back()]) dq.pop_back(); 243 | dq.push_back(i); 244 | res.push_back(nums[dq.front()]); 245 | } 246 | return res; 247 | } 248 | ``` 249 | -------------------------------------------------------------------------------- /Leetcode/stack.md: -------------------------------------------------------------------------------- 1 | ### Stack 2 | - [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) 🟢 EASY 🔵 Stack 3 | 4 | **Time O(N) + Space O(N)** 5 | ```cpp 6 | bool isValid(string s) { 7 | stack stack; 8 | for(auto c: s){ 9 | if(c == '(' || c == '[' || c == '{') 10 | stack.push(c); 11 | else{ 12 | if(stack.empty()) return false; 13 | char top = stack.top(); 14 | if(top == '(' && c != ')' || (top == '{' && c != '}')|| (top == '[' && c != ']')) 15 | return false; 16 | stack.pop(); 17 | } 18 | } 19 | return stack.empty(); 20 | } 21 | ``` 22 | - [155. Min Stack](https://leetcode.com/problems/min-stack/) 🟠 MEDIUM 🔵 Stack 23 | 24 | **Time O(1) + Space O(N)** 25 | ```cpp 26 | ::stack stack; 27 | ::stack> minstack; 28 | MinStack() { } 29 | 30 | void push(int val) { 31 | stack.push(val); 32 | if(minstack.empty() || val < minstack.top().first) minstack.push({val, 1}); 33 | else if(val == minstack.top().first) minstack.top().second++; 34 | } 35 | 36 | void pop() { 37 | if(stack.top() == minstack.top().first) minstack.top().second--; 38 | if(minstack.top().second == 0) minstack.pop(); 39 | stack.pop(); 40 | } 41 | 42 | int top() { 43 | return stack.top(); 44 | } 45 | 46 | int getMin() { 47 | return minstack.top().first; 48 | } 49 | ``` 50 | - [150. Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) 🟠 MEDIUM 🔵 Stack 51 | 52 | **Time O(N) + Space O(N)** 53 | ```cpp 54 | bool isOP(string c){ 55 | return c == "+" || c == "-" || c == "*" || c == "/"; 56 | } 57 | int calc(int a, string c, int b){ 58 | if(c == "+") return a + b; 59 | if(c == "-") return a - b; 60 | if(c == "*") return a * b; 61 | if(c == "/") return a / b; 62 | return 0; 63 | } 64 | int evalRPN(vector& tokens) { 65 | stack op; 66 | stack num; 67 | for(auto i : tokens){ 68 | if(isOP(i)){ 69 | int n1 = num.top(); 70 | num.pop(); 71 | int n2 = num.top(); 72 | num.pop(); 73 | num.push(calc(n2, i, n1)); 74 | }else{ 75 | num.push(stoi(i)); 76 | } 77 | } 78 | return num.top(); 79 | } 80 | ``` 81 | - [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) 🟠 MEDIUM 🔵 Stack 🔵 Backtrace 82 | 83 | 84 | Time O(4^N / sqrt(N)) + Space O(N) [_Explanation_](https://leetcode.com/problems/generate-parentheses/editorial/) 85 | ```cpp 86 | vector res; 87 | int n; 88 | void backtrack(int left, int leftcnt, string w){ 89 | if(w.size() == n * 2){ 90 | res.push_back(w); 91 | return ; 92 | } 93 | if(left == 0 && leftcnt < n) { 94 | backtrack(left + 1, leftcnt + 1, w + "("); 95 | }else{ 96 | if(leftcnt < n) backtrack(left + 1, leftcnt + 1, w + "("); 97 | backtrack(left - 1, leftcnt, w + ")"); 98 | } 99 | } 100 | vector generateParenthesis(int n) { 101 | this->n = n; 102 | backtrack(0, 0, ""); 103 | return res; 104 | } 105 | ``` 106 | - [225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/) 🟠 MEDIUM 🔵 Stack 🔵 Queue 107 | 108 | ```cpp 109 | queue q1; 110 | queue q2; 111 | 112 | void push(int x) { 113 | while(!q1.empty()) { 114 | q2.push(q1.front()); 115 | q1.pop(); 116 | } 117 | q1.push(x); 118 | while(!q2.empty()){ 119 | q1.push(q2.front()); 120 | q2.pop(); 121 | } 122 | } 123 | 124 | int pop() { 125 | int top = q1.front(); 126 | q1.pop(); 127 | return top; 128 | } 129 | 130 | int top() { 131 | return q1.front(); 132 | } 133 | 134 | bool empty() { 135 | return q1.empty(); 136 | } 137 | ``` 138 | 139 | ### Mono Stack 140 | - [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) 141 | - [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) 142 | - [907. Sum of Subarray Minimums](https://leetcode.com/problems/sum-of-subarray-minimums/) 🟠 MEDIUM 🔵 Mono Stack 143 | 144 | **Time O(N) + Space O(N)** 145 | ```cpp 146 | int sumSubarrayMins(vector& arr) { 147 | int MOD = 1000000007; 148 | stack stack; 149 | long minSum = 0; 150 | for(int i = 0; i <= arr.size(); i++){ 151 | while(!stack.empty() && (i == arr.size() || arr[stack.top()] >= arr[i])){ 152 | int mid = stack.top(); stack.pop(); 153 | int leftBound = stack.empty() ? -1 : stack.top(); 154 | int rightBound = i; 155 | long count = (mid - leftBound) * (rightBound - mid) % MOD; 156 | minSum += (count * arr[mid]) % MOD; 157 | minSum %= MOD; 158 | } 159 | stack.push(i); 160 | } 161 | return (int)minSum; 162 | } 163 | ``` 164 | - [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) 🟠 MEDIUM 🔵 Mono Stack 165 | ```cpp 166 | vector dailyTemperatures(vector& temperatures) { 167 | stack stack; 168 | vector res(temperatures.size(), 0); 169 | for(int curDay = 0; curDay < temperatures.size(); curDay++){ 170 | while(!stack.empty() && temperatures[stack.top()] < temperatures[curDay]){ 171 | int prevDay = stack.top(); stack.pop(); 172 | res[prevDay] = curDay - prevDay; 173 | } 174 | stack.push(curDay); 175 | } 176 | return res; 177 | } 178 | ``` 179 | - [Online Stock Span](https://leetcode.com/problems/online-stock-span/) 🟠 MEDIUM 🔵 Mono Stack 180 | 181 | **Time O(N) + Space O(N)** 182 | ```cpp 183 | stack> stack; 184 | StockSpanner() { } 185 | 186 | int next(int price) { 187 | int cnt = 1; 188 | while(!stack.empty() && stack.top().first <= price){ 189 | cnt += stack.top().second; 190 | stack.pop(); 191 | } 192 | stack.push({price, cnt}); 193 | return cnt; 194 | } 195 | ``` 196 | - [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/) 🟠 MEDIUM 🔵 Mono Stack 197 | 198 | **Time O(N) + Space O(N)** 199 | ```cpp 200 | vector nextGreaterElements(vector& nums) { 201 | stack stack; 202 | vector res(nums.size(), -1); 203 | int n = nums.size(); 204 | for(int curIdx = 0; curIdx < n * 2; curIdx++){ 205 | int curVal = nums[curIdx % n]; 206 | while(!stack.empty() && nums[stack.top()] < curVal){ 207 | int prevIdx = stack.top(); stack.pop(); 208 | res[prevIdx] = curVal; 209 | } 210 | stack.push(curIdx % n); 211 | } 212 | return res; 213 | } 214 | ``` 215 | - [853. Car Fleet](https://leetcode.com/problems/car-fleet/) 🟠 MEDIUM 🔵 Mono Stack 216 | 217 | **Time O(N) + Space O(N)** 218 | ```cpp 219 | int carFleet(int target, vector& position, vector& speed) { 220 | vector> nums; //position & speed 221 | for(int i = 0; i < position.size(); i++) nums.push_back({position[i], speed[i]}); 222 | sort(nums.begin(), nums.end()); 223 | for(auto p : nums) 224 | cout << "{" << p.first << ", " << p.second << "}, "; 225 | 226 | stack stack; 227 | for(int i = nums.size() - 1; i >= 0; i--){ 228 | double time = (target - nums[i].first) / (double)nums[i].second; 229 | if(stack.empty() || stack.top() < time) 230 | stack.push(time); // since it will never catch up 231 | } 232 | return stack.size(); 233 | } 234 | ``` 235 | ### Queue 236 | - [622. Deisgn Circular Queue](https://leetcode.com/problems/design-circular-queue/description/) 🟠 MEDIUM 🔵 Queue 237 | ```cpp 238 | vector buffer; 239 | int front, rear, size, cap; 240 | MyCircularQueue(int k) : buffer(k), front(0), rear(0), size(0), cap(k) {} 241 | 242 | bool enQueue(int value) { 243 | if(size == cap) return false; 244 | buffer[rear % cap] = value; 245 | rear++; 246 | size++; 247 | return true; 248 | } 249 | 250 | bool deQueue() { 251 | if(size == 0) return false; 252 | front++; 253 | size--; 254 | return true; 255 | 256 | } 257 | 258 | int Front() { 259 | return size == 0 ? -1 : buffer[front % cap]; // current front 260 | } 261 | 262 | int Rear() { 263 | return size == 0 ? -1 : buffer[(rear - 1) % cap]; // rear mean next elemnt spot 264 | } 265 | 266 | bool isEmpty() { 267 | return size == 0; 268 | } 269 | 270 | bool isFull() { 271 | return size == cap; 272 | } 273 | ``` 274 | -------------------------------------------------------------------------------- /Leetcode/two-pointers.md: -------------------------------------------------------------------------------- 1 | # Two Pointers (2 Pointer) Techniques in LeetCode Problems 2 | 3 | ## I.Opposite-direction Pointers: 4 | 5 | - [Leetcode 125. Valid Palindrome (I)](https://leetcode.com/problems/valid-palindrome/) **[EASY]** 6 | ```cpp 7 | bool isPalindrome(string s) { 8 | int l = 0, r = s.size() - 1; 9 | while(l < r){ 10 | while(l < r && !isalnum(s[l])) l++; 11 | while(l < r && !isalnum(s[r])) r--; 12 | if(tolower(s[l]) != tolower(s[r])) return false; 13 | l++, r--; 14 | } 15 | return true; 16 | } 17 | ``` 18 | - [Leetcode 125. Valid Palindrome (II)](https://leetcode.com/problems/valid-palindrome-ii/) **[EASY]** 19 | ```cpp 20 | bool helper(string s, int l, int r){ 21 | while(l < r){ 22 | if(s[l] != s[r]) return false; 23 | l++, r--; 24 | } 25 | return true; 26 | } 27 | bool validPalindrome(string s) { 28 | int l = 0, r = s.size() - 1; 29 | while(l < r){ 30 | if(s[l] != s[r]) return helper(s, l + 1, r) || helper(s, l, r - 1); 31 | l++, r--; 32 | } 33 | return true; 34 | } 35 | ``` 36 | - [Leetcode 1216. Valid Palindrome (III)](https://leetcode.com/problems/valid-palindrome-iii/) **[HARD]** 37 | ```cpp 38 | vector> memo; 39 | 40 | // Helper function to find the minimum deletions required to make the substring a palindrome 41 | int findMinDeletions(string &s, int l, int r) { 42 | if (l >= r) return 0; 43 | if (memo[l][r] != -1) return memo[l][r]; // Return cached result 44 | 45 | if (s[l] == s[r]) memo[l][r] = findMinDeletions(s, l + 1, r - 1); 46 | else memo[l][r] = 1 + min(findMinDeletions(s, l + 1, r), findMinDeletions(s, l, r - 1)); 47 | 48 | return memo[l][r]; 49 | } 50 | 51 | bool isValidPalindrome(string s, int k) { 52 | int n = s.length(); 53 | memo.assign(n, vector(n, -1)); 54 | return findMinDeletions(s, 0, n - 1) <= k; 55 | } 56 | ``` 57 | 58 | - [Leetcode 2330. Valid Palindrome (IV)](https://leetcode.com/problems/valid-palindrome-iv/) **[MED]** 59 | ```cpp 60 | bool makePalindrome(string s) { 61 | int l = 0, r = s.size() - 1, cnt = 2; 62 | while(l < r){ 63 | if(s[l] != s[r]){ 64 | if(--cnt < 0) return false; 65 | } 66 | l++, r--; 67 | } 68 | return true; 69 | } 70 | ``` 71 | - [Leetcode 5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) 72 | - [Leetcode 647. Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) **[MED]** 73 | ```cpp 74 | int countSubstrings(string s) { 75 | if(s.size() == 0 ) return 0; 76 | int cnt = 0; 77 | for(int i = 0; i < s.size(); i++){ 78 | for(int l = i, r = i; l >= 0 && r < s.size() && s[l] == s[r]; l--, r++) 79 | cnt ++; 80 | for(int l = i, r = i + 1; l >= 0 && r < s.size() && s[l] == s[r]; l--, r++) 81 | cnt ++; 82 | } 83 | return cnt; 84 | } 85 | ``` 86 | 87 | ## II. Meeting-in-the-middle Pointers: 88 | 89 | - [Leetcode 1. Two Sum (using a two-pointer algorithm with sorting)](https://leetcode.com/problems/two-sum/) **[EASY]** 90 | 91 | **HashMap ```O(N)``` + ```O(N)```** 92 | ```cpp 93 | vector twoSum(vector& nums, int target) { 94 | unordered_map mp; 95 | for(int i = 0; i < nums.size(); i++){ 96 | if(mp.find(target - nums[i]) != mp.end()) return {mp[target - nums[i]], i}; 97 | else mp[nums[i]] = i; 98 | } 99 | return {-1, -1}; 100 | } 101 | ``` 102 | - [Leetcode 167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) **[MED]** 103 | 104 | **```O(N)``` + ```O(1)```** 105 | ```cpp 106 | vector twoSum(vector& nums, int target) { 107 | int l = 0, r = nums.size() - 1; 108 | while(l < r){ 109 | int sum = nums[l] + nums[r]; 110 | if(sum == target) return {l + 1, r + 1}; 111 | if(sum > target) r--; 112 | else l++; 113 | } 114 | return {-1, -1}; 115 | } 116 | ``` 117 | - [Leetcode 15. 3Sum](https://leetcode.com/problems/3sum/) **[MED]** 118 | 119 | **Two Pointers: Time -> ```O(N*2)``` + Space -> ```O(logN)``` ~ ```O(N)```, depends on sorting algo** 120 | ```cpp 121 | vector> threeSum(vector& nums) { 122 | vector> res; 123 | sort(nums.begin(), nums.end()); 124 | for(int i = 0; i <= nums.size() - 3 && nums[i] <= 0; i++){ 125 | if(i > 0 && nums[i - 1] == nums[i]) continue; 126 | int j = i + 1, k = nums.size() - 1; 127 | int target = -nums[i]; 128 | while(j < k){ 129 | int sum = nums[j] + nums[k]; 130 | if(sum > target) k--; 131 | else if(sum < target) j++; 132 | else{ 133 | res.push_back({nums[i], nums[j++], nums[k--]}); 134 | while(j < k && nums[j] == nums[j - 1]) j++; 135 | } 136 | } 137 | } 138 | return res; 139 | } 140 | ``` 141 | 142 | **No-Sort + HashMap: ```O(N*2)``` + ```O(N)```** 143 | ```cpp 144 | vector> threeSum(vector& nums) { 145 | set> res; 146 | unordered_set dups; 147 | unordered_map seen; 148 | for(int i = 0; i < nums.size(); i++){ 149 | if (dups.insert(nums[i]).second) { 150 | for(int j = i + 1; j < nums.size(); j++){ 151 | int comp = -nums[i] - nums[j]; 152 | auto it = seen.find(comp); 153 | if(it != seen.end() && it->second == i){ 154 | vector trip = {nums[i], nums[j], comp}; 155 | sort(trip.begin(), trip.end()); 156 | res.insert(trip); 157 | } 158 | seen[nums[j]] = i; // i has a match with j 159 | } 160 | } 161 | } 162 | return vector>(begin(res), end(res)); 163 | } 164 | ``` 165 | - [Leetcode 16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/) **[MED]** 166 | 167 | **Time : ```O(NlogN)``` + ```O(N^2)``` = ```O(N^2)``` | Space : ```O(logN)``` ~ ```O(N)```, depends on sorting algo** 168 | 169 | ```cpp 170 | int threeSumClosest(vector& nums, int target) { 171 | sort(nums.begin(), nums.end()); 172 | int dif = INT_MAX; 173 | int res = target; 174 | for(int i = 0; i < nums.size(); i++){ 175 | int j = i + 1, k = nums.size() - 1; 176 | while(j < k){ 177 | int sum = nums[i] + nums[j] + nums[k]; 178 | dif = abs(target - sum) < abs(dif) ? target - sum : dif; 179 | if(dif == 0) return target - dif; 180 | if(sum > target) k--; 181 | else if(sum < target) j++; 182 | } 183 | } 184 | return target - dif; 185 | } 186 | ``` 187 | - [Leetcode 18. 4Sum](https://leetcode.com/problems/4sum/) 188 | 189 | **Time : ```O(N*3)``` | Space : ```O(logN)``` ~ ```O(N)```, depends on sorting algo** 190 | ```cpp 191 | vector> fourSum(vector& nums, int target) { 192 | sort(nums.begin(), nums.end()); 193 | vector> res; 194 | int n = nums.size(); 195 | for(int i = 0; i < n - 3; i++){ 196 | if (i > 0 && nums[i] == nums[i-1]) continue; // Skip duplicate i values 197 | for(int j = i + 1; j < n - 2; j++){ 198 | if (j > i + 1 && nums[j] == nums[j-1]) continue; // Skip duplicate j values 199 | long long newTarget = (long long)target - (long long)nums[i] - (long long)nums[j]; 200 | int low = j + 1, high = n - 1; 201 | while(low < high){ 202 | int sum = nums[low] + nums[high]; 203 | if (sum < newTarget) 204 | low++; 205 | else if (sum > newTarget) 206 | high--; 207 | else { 208 | res.push_back({nums[i], nums[j], nums[low], nums[high]}); 209 | while (low < high && nums[low] == nums[low + 1]) low++; // Skip duplicate low values 210 | while (low < high && nums[high] == nums[high - 1]) high--; // Skip duplicate high values 211 | low++; 212 | high--; 213 | } 214 | } 215 | } 216 | } 217 | return res; 218 | } 219 | ``` 220 | - [Leetcode 454. 4Sum II](https://leetcode.com/problems/4sum-ii/) **[MED]** 221 | 222 | **For 4 arrays:** 223 | ```cpp 224 | int fourSumCount(vector& A, vector& B, vector& C, vector& D) { 225 | int cnt = 0; 226 | unordered_map m; 227 | for (int a : A) { 228 | for (int b : B) { 229 | ++m[a + b]; 230 | } 231 | } 232 | 233 | for (int c : C) { 234 | for (int d : D) { 235 | auto it = m.find(-(c + d)); 236 | if (it != end(m)) { 237 | cnt += it->second; 238 | } 239 | } 240 | } 241 | return cnt; 242 | } 243 | ``` 244 | 245 | **For N arrays:** 246 | ```cpp 247 | // Function to compute sum counts for a list of vectors 248 | unordered_map sumCount(vector>& lists) { 249 | unordered_map res = {{0, 1}}; // Initialize with sum 0 having count 1 250 | for (auto& list : lists) { 251 | unordered_map temp; 252 | for (int num : list) { 253 | for (auto& [total, count] : res) { 254 | temp[total + num] += count; 255 | } 256 | } 257 | res = move(temp); // Move temp to res for the next iteration 258 | } 259 | return res; 260 | } 261 | 262 | int fourSumCount(vector& A, vector& B, vector& C, vector& D) { 263 | // Split the original lists into two halves 264 | vector> firstHalf = {A, B}; 265 | vector> secondHalf = {C, D}; 266 | 267 | // Get sum counts for each half 268 | auto left = sumCount(firstHalf); 269 | auto right = sumCount(secondHalf); 270 | 271 | int result = 0; 272 | // Calculate the final count by multiplying complementary sum counts 273 | for (auto& [sum, count] : left) { 274 | if (right.find(-sum) != right.end()) { 275 | result += count * right[-sum]; 276 | } 277 | } 278 | 279 | return result; 280 | } 281 | ``` 282 | 283 | - [Leetcode 277. Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/) **[MED]** 284 | 285 | **Time : ```O(N)``` + Space : ```O(1)```** 286 | ```cpp 287 | int findCelebrity(int n) { 288 | int celebrity_candidate = 0; 289 | for(int i = 0; i < n; i++){ 290 | if(knows(celebrity_candidate, i)) 291 | celebrity_candidate = i; 292 | } 293 | for(int j = 0; j < n; j++){ 294 | if(j == celebrity_candidate) continue; 295 | if(knows(celebrity_candidate, j) || !knows(j, celebrity_candidate)) return -1; 296 | } 297 | return celebrity_candidate; 298 | } 299 | ``` 300 | - [Leetcode 11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/) **[MED]** 301 | 302 | **Time : ```O(N)``` + Space : ```O(1)```** 303 | ```cpp 304 | int maxArea(vector& height) { 305 | int l = 0, r = height.size() - 1; 306 | int maxArea = 0; 307 | while(l < r){ 308 | int lHeight = height[l], rHeight = height[r]; 309 | int curArea = (r - l) * min(lHeight, rHeight); 310 | maxArea = max(maxArea, curArea); 311 | if(lHeight < rHeight) l++; 312 | else r--; 313 | } 314 | return maxArea; 315 | } 316 | ``` 317 | - [Leetcode 186 Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) **[MED]** 318 | 319 | **Time : ```O(N)``` + Space : ```O(1)```** 320 | ```cpp 321 | void swap(char* i, char* j){ 322 | char temp = *i; 323 | *i = *j; 324 | *j = temp; 325 | } 326 | void reverseWords(vector& s) { 327 | for(int l = 0, r = s.size() - 1; l < r; l++, r--) swap(&s[l], &s[r]); 328 | 329 | int i = 0; 330 | while(i < s.size()){ 331 | int j = i; 332 | while(j < s.size() && s[j] != ' ') j++; 333 | for(int l = i, r = j - 1; l < r; l++, r--) swap(&s[l], &s[r]); 334 | i = j + 1; 335 | } 336 | } 337 | ``` 338 | 339 | ## III. Same-direction Pointers: 340 | 341 | - [Leetcode 283. Move Zeroes](https://leetcode.com/problems/move-zeroes/) 342 | - [Leetcode 26. Remove Duplicate Numbers in Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) 343 | - [Leetcode 395. Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) **[MED]** 344 | 345 | **Time : ```O(26 * N)``` = ```O(N)``` | Space : ```O(1)```** 346 | ```cpp 347 | int longestSubstring(string s, int k) { 348 | // Step 1: Calculate the total number of unique characters in the string. 349 | unordered_set uniqueCharsSet(s.begin(), s.end()); 350 | int totalUnique = uniqueCharsSet.size(); 351 | 352 | int maxLen = 0; 353 | 354 | // Step 2: Apply sliding window technique for each possible number of unique target characters. 355 | for (int uniqueTarget = 1; uniqueTarget <= totalUnique; ++uniqueTarget) { 356 | vector freq(26, 0); 357 | int start = 0, end = 0; 358 | int uniqueChars = 0, charsAtLeastK = 0; 359 | while (end < s.length()) { 360 | if (uniqueChars <= uniqueTarget) { 361 | int index = s[end] - 'a'; 362 | if (freq[index]++ == 0) uniqueChars++; 363 | if (freq[index] == k) charsAtLeastK++; 364 | end++; 365 | } else { 366 | int index = s[start] - 'a'; 367 | if (freq[index]-- == k) charsAtLeastK--; 368 | if (freq[index] == 0) uniqueChars--; 369 | start++; 370 | } 371 | 372 | if (uniqueChars == uniqueTarget && uniqueChars == charsAtLeastK) { 373 | maxLen = max(maxLen, end - start); 374 | } 375 | } 376 | } 377 | 378 | return maxLen; 379 | } 380 | ``` 381 | - [Leetcode 340. Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) **[MED]** 382 | 383 | **Time : ```O(N)``` * ```O(N - 1)``` = ```O(N)``` | Space : ```O(1)```** 384 | ```cpp 385 | int lengthOfLongestSubstringKDistinct(string s, int k) { 386 | unordered_map cnt; 387 | int start = 0, end = 0, maxLen = 0; 388 | while(end < s.size()){ 389 | char endc = s[end]; 390 | if(cnt.find(endc) == cnt.end()) cnt[endc] = 1; 391 | else cnt[endc]++; 392 | 393 | while(cnt.size() > k){ 394 | if(--cnt[s[start]] == 0) cnt.erase(s[start]); 395 | start++; 396 | } 397 | maxLen = std::max(maxLen, end - start + 1); 398 | end++; 399 | } 400 | return maxLen; 401 | } 402 | ``` 403 | - [Leetcode 424. Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) 404 | 405 | **Time : ```O(N)``` | Space : ```O(1)```** 406 | ```cpp 407 | int characterReplacement(string s, int k) { 408 | vector freqMap(26, 0); 409 | int start = 0, maxFreq = 0, maxLen = 0; 410 | for(int end = 0; end < s.size(); end++){ 411 | int curChar = s[end] - 'A'; 412 | maxFreq = max(maxFreq, ++freqMap[curChar]); 413 | bool isValid = (end - start + 1 - maxFreq <= k); 414 | if(!isValid){ 415 | int removeChar = s[start] - 'A'; 416 | freqMap[removeChar]--; 417 | start++; 418 | } 419 | maxLen = end + 1 - start; 420 | } 421 | return maxLen; 422 | } 423 | ``` 424 | - [Leetcode 76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) 425 | 426 | **Time : ```O(N)``` | Space : ```O(1)```** 427 | ```cpp 428 | string minWindow(string s, string t) { 429 | vector t_map(128, 0); 430 | for (char c : t) t_map[c]++; 431 | 432 | int left = 0, right = 0; 433 | int min_len = INT_MAX, min_start = 0, found_chars = 0; 434 | while (right < s.size()) { 435 | if (t_map[s[right]] > 0) found_chars++; 436 | t_map[s[right]]--; 437 | 438 | while (found_chars == t.size()) { 439 | if (right - left + 1 < min_len) { 440 | min_len = right - left + 1; 441 | min_start = left; 442 | } 443 | if (t_map[s[left]] == 0)found_chars--; 444 | t_map[s[left++]]++; 445 | } 446 | right++; 447 | } 448 | 449 | return min_len == INT_MAX ? "" : s.substr(min_start, min_len); 450 | } 451 | ``` 452 | - [Leetcode 3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 453 | 454 | **Time : ```O(N)``` | Space : ```O(1)```** 455 | ```cpp 456 | int lengthOfLongestSubstring(string s) { 457 | vector seen(128, false); 458 | int start = 0, maxLen = 0; 459 | for(int end = 0; end < s.size(); end++){ 460 | if(seen[s[end]] == false) seen[s[end]] = true; 461 | else{ 462 | while(s[end] != s[start]) seen[s[start++]] = false; 463 | start++; 464 | } 465 | maxLen = max(maxLen, end - start + 1); 466 | } 467 | return maxLen; 468 | } 469 | ``` 470 | - [Leetcode 1004 Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) 471 | 472 | **Time : ```O(N)``` | Space : ```O(1)```** 473 | ```cpp 474 | int longestOnes(vector& nums, int k) { 475 | int maxLen = 0, left = 0; 476 | for(int right = 0; right < nums.size(); right++){ 477 | if(nums[right] == 0){ 478 | if(--k < 0){ 479 | while(nums[left] != 0) left++; 480 | left++; 481 | k++; 482 | } 483 | } 484 | maxLen = max(maxLen, right - left + 1); 485 | } 486 | return maxLen; 487 | } 488 | ``` 489 | - [Leetcode 1658 Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) **[MED]** 490 | 491 | > The core idea is to transform the problem into finding the **maximum-length subarray** whose sum equals **total_sum - x** 492 | 493 | **Time : ```O(N)``` | Space : ```O(1)```** 494 | ```cpp 495 | int minOperations(vector& nums, int x) { 496 | int sum = 0; 497 | for(int n : nums) sum += n; 498 | 499 | int maxLen = -1, curSum = 0; 500 | for(int l = 0, r = 0; r < nums.size(); r++){ 501 | curSum += nums[r]; 502 | while(l <= r && curSum > sum - x) curSum -= nums[l++]; 503 | if(curSum == sum - x) maxLen = max(maxLen, r - l + 1); 504 | } 505 | 506 | return maxLen == -1 ? -1 : nums.size() - maxLen; 507 | } 508 | ``` 509 | -------------------------------------------------------------------------------- /OS/Network-KernelvsUser.md: -------------------------------------------------------------------------------- 1 | Catelog 2 | 3 | - Coding Basics in C/C++ 4 | 5 | - OS 6 | - concurrency 7 | - Networking fundamentals✅ 8 | - Boundaries, Alignments, Pointers, 9 | - bit operation 10 | - Pointers 11 | - Boundaries 12 | - Byte Alignments 13 | - Protocols ✅ 14 | - User Space vs Kernel Space ✅ 15 | - Memory 16 | - Memory Mapping 17 | - Dynamic Memory Allocations (HW1) 18 | 19 | ## C Programming Language 20 | 21 | - Data Type and initialization 22 | 23 | - Primary Data Types & Range 24 | 25 | ![Screenshot 2024-03-03 at 10.00.21 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-03 at 10.00.21 PM.png) 26 | 27 | ![Screenshot 2024-03-03 at 10.02.09 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-03 at 10.02.09 PM.png) 28 | 29 | - User Defined types 30 | 31 | - struct 32 | 33 | ```c 34 | struct Person { 35 | char name[50]; 36 | int age; 37 | float salary; 38 | }; 39 | 40 | int main() { 41 | // direct assignment 42 | struct Person person1; 43 | strcpy(person1.name, "John Doe"); // Assuming string.h is included 44 | person1.age = 30; 45 | person1.salary = 50000.0; 46 | 47 | // direct declaration 48 | struct Person person2 = {"John Doe", 30, 50000.0}; 49 | 50 | // designated initializers 51 | struct Person person3 = {.age = 30, .salary = 50000.0, .name = "John Doe"}; 52 | 53 | // zero or null 54 | struct Person person3 = {0}; 55 | memset(&person1, 0, sizeof(person1)); 56 | 57 | } 58 | 59 | ``` 60 | 61 | - typedef 62 | 63 | ```c 64 | typedef unsigned long ulong; 65 | 66 | int main() { 67 | ulong number = 5000; 68 | } 69 | 70 | ``` 71 | 72 | - union 73 | 74 | ```c 75 | union Data { 76 | int i; 77 | float f; 78 | char str[20]; 79 | }; 80 | 81 | int main() { 82 | union Data data; 83 | data.i = 10; 84 | } 85 | 86 | 87 | - Enum 88 | 89 | ```c 90 | enum weekday {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; 91 | 92 | int main() { 93 | enum weekday today = Wednesday; 94 | } 95 | 96 | ``` 97 | 98 | 99 | 100 | - **Storage Types** 101 | 102 | > ![Screenshot 2024-03-03 at 10.12.03 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-03 at 10.12.03 PM.png) 103 | > 104 | > C Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility, and lifetime which help us to trace the existence of a particular variable during the runtime of a program. 105 | 106 | - **auto**: Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). 107 | 108 | - **extern**: 109 | 110 | declare a global variable or function in another file. 111 | 112 | ```c 113 | // File1.c 114 | extern int globalVar; // Declaration of a global variable that is defined in File2.c 115 | 116 | // File2.c 117 | int globalVar = 5; // Definition of globalVar 118 | ``` 119 | 120 | - **static**: 121 | 122 | `static` variables or functions are local to the block where they are defined, but their values are preserved between function calls. 123 | 124 | ```c 125 | void function() { 126 | static int count = 0; // This variable retains its value between function calls 127 | count++; 128 | printf("%d ", count); 129 | } 130 | 131 | int main() { 132 | function(); // Prints: 1 133 | function(); // Prints: 2 134 | } 135 | ``` 136 | 137 | - **Register**: 138 | 139 | `register` suggests that the variable should be stored in a register instead of RAM to optimize access speed. The keyword is mostly advisory, as the compiler's optimizer can override the suggestion. 140 | 141 | ```c 142 | int main() { 143 | register int miles = 100; 144 | } 145 | ``` 146 | 147 | - qsort 148 | 149 | ```c 150 | typedef struct { 151 | char title[50]; 152 | int pages; 153 | float price; 154 | } book; 155 | int compareBook(book b1, book b2){ 156 | if(b1.price < b2.price){ 157 | return 0; 158 | } 159 | return 1; 160 | } 161 | int main(){ 162 | book book_arr[5]; 163 | qsort((void*)book_arr, 5, sizeof(book_arr[0]), compareBook); 164 | } 165 | ``` 166 | 167 | 168 | 169 | - Conditionals 170 | 171 | - goto 172 | - if 173 | - else 174 | - case switch 175 | - default 176 | 177 | - loops & loops controls 178 | 179 | - for 180 | - do 181 | - while 182 | - continue 183 | - break 184 | 185 | - Others 186 | 187 | - const 188 | - sizeof 189 | - Volatile 190 | 191 | - Memory allocation 192 | 193 | - Struct 194 | 195 | - Union 196 | 197 | - Socket & File/IO interface 198 | 199 | ## Network Engineering 200 | 201 | - **Questions**: 202 | 203 | - Router vs Gateway 204 | 205 | - **Gateway** : focus on protocol conversion and facilitating communications across different networks, 206 | - **Routers** : focus on data packet forwarding and network traffic management within and between networks. 207 | 208 | - Router vs Switch 209 | 210 | - **Router**: Connects multiple networks and directs data packets between them using IP addresses. It determines the best path for data to travel across networks. 211 | - **Switch**: Connects devices within a single network, using MAC addresses to forward data packets directly to the intended device on the local network. 212 | 213 | - what happens when you type a URL into a web browser 214 | 215 | 1. **Browser looks up IP address for the domain** 216 | 217 | - Browser sends a request to the DNS (domain name system) server. 218 | - DNS sends back the sever IP address 219 | 220 | 2. **Browser sends the HTTP request to the server** 221 | 222 | - **Initiating Communication (Application Layer)**: The user's request is prepared at the application layer using a protocol like HTTPS, which involves formatting the data packet for transport, often including secure encryption through TLS/SSL to ensure data privacy. 223 | 224 | - **Data Encapsulation (Transport Layer)**: The data is segmented (if necessary) and encapsulated with the necessary headers for transport. TCP or UDP protocols are used, depending on the requirements for reliability and speed. TCP provides error correction and sequence management, while UDP is faster but less reliable. 225 | 226 | - **Data Transmission (Network Layer)**: The data packets are sent across the internet, guided by the Internet Protocol (IP). Packets may travel through multiple routers, each making routing decisions to move the packets closer to their destination based on IP addresses. 227 | - Packet Transmission in Routers 228 | - **Receiving Data Packets**: Routers interface with multiple networks and first receive incoming data packets from one of these networks. 229 | - **Examining Packet Headers**: Each data packet contains header information, including the destination IP address. The router examines this header to determine the packet's destination. 230 | - **Routing Table Lookup**: The router uses the destination IP address to consult its routing table and find the best next hop towards the packet's destination. Routing tables contain entries for known networks, the directions (or interfaces) in which those networks can be reached, and the distance or metric to those networks, helping the router make efficient routing decisions. 231 | - **Forwarding Decision**: forwards the packet to the next network on its journey. This decision is based on algorithms that consider factors such as the number of hops, network congestion, and path reliability. 232 | - **Packet Transmission**: The router sends the packet out through the appropriate interface towards its next hop. This process repeats across multiple routers until the packet reaches its final destination. 233 | 234 | - **Physical and Link Layers**: At the lowest levels, the physical and data link layers handle the actual transmission of data over physical networks and the direct connection between devices, using protocols appropriate to the medium (e.g., Ethernet for LANs). 235 | 236 | 3. **Server Processing**: The server receives the request and processes it. This might involve load balancing across multiple servers, database queries, or dynamic content generation before the requested document (webpage) is served back to the client. 237 | 238 | 4. **Data Reception and Display**: The client's browser receives the data, which is then rendered as a webpage. This may involve additional requests for resources like images, CSS, or JavaScript files to fully assemble the page. 239 | 240 | - **Basic** 241 | 242 | - **A router acts as a gateway to the computer network** and is placed between a modem and a switch or hub 243 | - **A switch connects devices** such as a desktop, laptop, and access point to the router. 244 | - **An access point connects a device wirelessly**. Sometimes modem, router, switch, and access point come all bundled in one device. 245 | 246 | - **Protcols** 247 | 248 | - **Protocols** are sets of rules for message formats and procedures that allow machines and application programs to exchange information. These rules must be followed by each machine involved in the communication in order for the receiving host to be able to understand the message. 249 | 250 | - **TCP/IP**: a family of communication protocols used to connect computer systems in a network. It is named after two of the protocols in the family: Transmission Control Protocol (TCP) and Internet Protocol (IP). Hypertext Transfer Protocol (HTTP) is a member of the TCP/IP family. 251 | 252 | - **Layers of protocols**: Application Layer, Transport Layer, Network Layer, Network Interface Layer, and Hardware. 253 | 254 | ![Screenshot 2024-03-02 at 8.49.14 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-02 at 8.49.14 PM.png) 255 | 256 | - Application Layer: messages or streams of data **(HTTP)** 257 | - Transport Layer: packets with a destination address **(TCP or UDP)** 258 | - Internet Network layer: encloses the packet in an **Internet Protocol** (**IP**) datagram, puts in the datagram header and trailer, decides where to send the datagram (either directly to a destination or else to a gateway) **(IP)** 259 | - Network Interface layer: accepts **IP** datagrams and transmits them as *frames*over a specific network hardware, such as Ethernet or Token-Ring networks. 260 | 261 | - **Host data transmissions and receptions**: 262 | 263 | ![Screenshot 2024-03-02 at 8.54.37 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-02 at 8.54.37 PM.png) 264 | 265 | - **Internet, TCP/IP and HTTP Concepts:** 266 | 267 | - **IP Address** 268 | 269 | - **Defintion**: Each server or client on a TCP/IP internet is identified by a numeric IP (Internet Protocol) address. 270 | - **Two Types**: 271 | - **IPv4 (IP version 4) address** 272 | - 128-bit addresses, usually expressed in hexadecimal notation 273 | - ```IP address in colon hexadecimal notation: 1:22:333:4444::abc0:def0 ``` 274 | - **IPv6 (IP version 6) address** 275 | - 32-bit addresses, usually expressed in dotted decimal notation 276 | - ```129.126.178.99``` 277 | 278 | - **Host names/Domain names** 279 | 280 | - A host, or website, on the Internet is identified by a host name, such as `www.example.com` 281 | - Host names are mapped to IP addresses 282 | - a host name and an IP address do not have a one-to-one relationship. 283 | 284 | - **Virtual Hosting** 285 | 286 | - HTTP includes the concept of virtual hosting, where a single HTTP server can represent multiple hosts at the same IP address. 287 | - You can use virtual hosting in web support by setting up URIMAP resources. 288 | 289 | - **Port Numbers** 290 | 291 | - In a server, more than one user process can use TCP at the same time. 292 | - To identify the data associated with each process, port numbers are used. 293 | - Port numbers are 16-bit, and numbers up to 65535 are possible 294 | 295 | - **URL (Components)** 296 | 297 | 1. **A scheme.** 298 | 299 | The scheme identifies the protocol to be used to access the resource on the Internet. It can be HTTP (without SSL) or HTTPS (with SSL). 300 | 301 | 2. **A host.** 302 | 303 | The host name identifies the host that holds the resource. For example, `www.example.com`. A server provides services in the name of the host, but hosts and servers do not have a one-to-one mapping. 304 | 305 | Host names can also be followed by a **port number**.Well-known port numbers for a service are normally omitted from the URL. Most servers use the well-known port numbers for HTTP and HTTPS , so most HTTP URLs omit the port number. 306 | 307 | 3. **A path.** 308 | 309 | The path identifies the specific resource in the host that the web client wants to access. For example, `/software/htp/cics/index.html`. 310 | 311 | 4. **A query string.** 312 | 313 | If a query string is used, it follows the path component, and provides a string of information that the resource can use for some purpose (for example, as parameters for a search or as data to be processed). T 314 | 315 | The query string is usually a string of name and value pairs; for example, `term=bluebird`. Name and value pairs are separated from each other by an ampersand (&); for example, `term=bluebird&source=browser-search`. 316 | 317 | - **HTTP Protocols** 318 | 319 | - **Def**: Web clients and srvers interact using a text-based application-level protocol hown as HTTP 320 | 321 | - **HTTP Transactions** 322 | 323 | - Client: **HTTP Request** 324 | 325 | - Request Line (form: | example: GET / HTTP/1.1) 326 | - methods: GET, POST, OPTIONS, HEAD, PUT, DELETE, and TRACE 327 | - URI: suffix of the URL that includes the filename and optional arguments 328 | - Request header(s) 329 | - empty line 330 | 331 | - Server: **HTTP Response** 332 | 333 | - Response line (form: | example: HTTP/1.0 200 ok) 334 | 335 | ![Screenshot 2024-03-02 at 8.40.00 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-02 at 8.40.00 PM.png) 336 | 337 | - **Web server provide content to clients:** 338 | 339 | - fetch a disk file (serving static content) 340 | 341 | - Run an executable file and return its output (serving dynamic content) 342 | 343 | - **How Does the Client Pass Program Arguments to the Server?** 344 | 345 | ```bash 346 | GET /cgi-bin/adder?15000&213 HTTP/1.1 347 | ``` 348 | 349 | - Arguments for GET requests are passed in the URI. As we have seen, a ‘?’ character separates the fifilename from the arguments, and each argument is separated by an ‘&’ character. 350 | 351 | - Spaces are not allowed in arguments and must be represented with the %20 string. 352 | 353 | 354 | 355 | - **Socket Interface** 356 | 357 | - **Definition**: Many TCP/IP implementations provide an application programming interface to the TCP protocol; that is, to the transport layer. This interface is commonly known as the *Sockets interface*.**** 358 | 359 | - ![Screenshot 2024-03-02 at 8.45.47 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-02 at 8.45.47 PM.png) 360 | 361 | 362 | 363 | ## Kernel VS User Space 364 | 365 | https://www.form3.tech/blog/engineering/linux-fundamentals-user-kernel-space 366 | 367 | - Diagram Illustration 368 | - ![Screenshot 2024-03-03 at 9.35.12 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-03 at 9.35.12 PM.png) 369 | - ![Screenshot 2024-03-03 at 9.34.49 PM](/Users/yizhenzhang/Library/Application Support/typora-user-images/Screenshot 2024-03-03 at 9.34.49 PM.png) 370 | 371 | 372 | 373 | - **Userspace vs Kernalspace** 374 | 375 | - **User Space vs Kernel Space (Memory)** 376 | - *User space* is that portion of system [*memory*](https://www.linfo.org/memory.html) in which *user processes* run. 377 | - This contrasts with [*kernel space*](https://www.linfo.org/kernel_space.html), which is that portion of memory in which the [*kernel*](https://www.linfo.org/kernel.html) executes and provides its services. 378 | 379 | - **User Mode vs Kernel Mode** 380 | - User space processes literally run in the user space part of memory. A user space process runs in [user mode](http://www.linfo.org/user_mode.html), which is the non-privileged execution mode that the process' instructions are executed with. 381 | - [Kernel space](http://www.linfo.org/kernel_space.html) is the area of system memory reserved for the kernel. It is where the kernel runs and executes kernel mode instructions.[Kernel mode](http://www.linfo.org/kernel_mode.html)is the CPU execution mode of the kernel, which runs in a privileged, root-access mode. 382 | - **Mode Switch** 383 | - User mode processes have to switch to kernel mode when they want to consume services provided by the kernel (e.g. disk I/O, network access). 384 | - When a user space application requires the services provided by the kernel, it will signal the kernel to execute a syscall, and switch to kernel mode for the duration of the syscall execution. 385 | - **Security**: User mode execution of user-run processes ensures that a user space process cannot access or modify memory managed by the kernel, and can't interfere with another process' execution. T 386 | 387 | - Memory: consisted of RAM (randomly accessed memory) 388 | - Storage (Disk drives) - whose contents are retained after the power is turned off and which usually has a far greater capacity. 389 | 390 | - **Syscalls** ```*man syscalls*``` 391 | - **Definition**: [Syscalls](http://www.linfo.org/system_call.html) are functions in the kernel that provide services to a user space application. They are the API that the kernel exposes to user space programs, which allow a program to utilise the functionality the kernel offers. 392 | - Examples 393 | - There are a variety of syscalls for socket-based networking (e.g. *socket*, *bind*, *listen*, and *accept*), which combined offer a suite of socket-based functions for user space programs to utilise. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /companys/compantlist.md: -------------------------------------------------------------------------------- 1 | ### Top FinTech 2 | 1. Plaid 3 | 2. PayJoy 4 | 3. Ramp 5 | 4. Tradeshift 6 | 5. Debbie 7 | 6. Nav.it 8 | 7. Tala 9 | 8. Stripe 10 | 9. OpenSea 11 | 10. Talos 12 | 11. Current 13 | 12. Mercury 14 | 13. Greenwood Bank 15 | 14. Dave 16 | 15. BillGO 17 | 16. Divvy Homes 18 | 17. Avalanche 19 | 18. CoinFlip 20 | 19. Stax Payments 21 | 20. Melio 22 | 21. Greenlight 23 | 22. Rocket Money 24 | 23. Nibble Health 25 | 24. Petal 26 | 25. GoodLeap 27 | 28 | ### Top Quant Trading 29 | 1. Two Sigma Investments 30 | 2. Citadel 31 | 3. D.E. Shaw & Co. 32 | 4. Renaissance Technologies 33 | 5. AQR Capital Management 34 | 6. Bridgewater Associates 35 | 7. Point72 Asset Management 36 | 8. Man AHL 37 | 9. Jump Trading 38 | 39 | ### Other Quant Trading 40 | 1.Timber Hill, 41 | 2. Gelber Group, 42 | 3. Hull Trading, 43 | 4. Optiver, 44 | 5. Susquehanna, 45 | 6. IMC, 46 | 7. Citadel, 47 | 8. Automated Trading Desk, 48 | 9. TGS Management Company, 49 | 10. DRW, 50 | 11. RGM Advisors, 51 | 12. Chopper, 13. Transmarket Group, 14. RSJ Trading, 15. Chicago Trading Company, 16. Peak6, 17. Quantlab, 18. Teza Technologies, 19. Tower Research, 20. Jump Trading, 21. Geneva Trading, 22. Jane Street, 23. Liquid Capital, 24. Final, 25. Source Capital, 26. Allston, 27. Hudson River Trading, 28. Sun Trading, 29. XR Trading, 30. Flow Traders, 31. Zomojo, 32. Tibra, 33. GRT, 34. Epoch Capital, 35. Virtue, 36. Nyenburgh, 37. Madison Tyle, 38. Getco, 39. Knight Capital, 40. Istra Research, 41. XTX Markets, 42. Automat, 43. Headlands, 44. Eladian Partners, 45. Akuna, 46. Maven, 47. Vivienne Court Trading, 48. Radix Trading, 49. Vatic Labs, 50. Domeyard. 52 | -------------------------------------------------------------------------------- /cpp/2. C++ Fundamentals.md: -------------------------------------------------------------------------------- 1 | Modern C++ Types 2 | 3 | - **Automatic type inference** (compiler figure out for you) 4 | 5 | ```cpp 6 | auto begin = studentMap.cbegin(); 7 | ``` 8 | 9 | - discard reference 10 | - lambda function: must use auto, for the type does not have the name 11 | - ```auto func = [](auto i) {return i*2};``` 12 | - cannot use auto as parameter 13 | - Pros: 14 | - avoid bug such as implicit conversions and unintizlied viarbales 15 | - change type easier 16 | 17 | - **Return multiple thing** 18 | 19 | - pair: store 2 elements 20 | 21 | - ```pair``` 22 | 23 | - tuple: store a fixed number of items, where each item can be of a different type. 24 | 25 | - ``` tuple myTuple = make_tuple("Example", 10, 3.14); ``` 26 | 27 | - sturtcured binidngs: immediately unpacking the variables in a pair 28 | 29 | ```cpp 30 | pair findPriceRange(int dist){ .. } 31 | auto [min, max] = findPriceRange(dist); 32 | ``` 33 | 34 | - struct: a collection of named vairbales group together 35 | 36 | ```cpp 37 | struct PriceRange { 38 | int min; 39 | int max; 40 | }; 41 | 42 | struct Course { 43 | string code; 44 | Time startTime; Time endTime; 45 | vector instructors; 46 | }; 47 | ``` 48 | 49 | 50 | 51 | - **Uniform/List Initialization** (C++ 11) 52 | 53 | ```cpp 54 | int main() { 55 | vector vec{3, 1, 4, 1, 5, 8}; 56 | Course courses{"CS102", {15, 30}, {16, 30}, {"Wang", "Zeng"}}; 57 | vector<> 58 | vector vec1{3}; // vector = {3}; -> list initulizer 59 | // other initizlier 60 | vector vec2(3); // vector = {0, 0, 0}; 61 | } 62 | ``` 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /cpp/3. STL.md: -------------------------------------------------------------------------------- 1 | Overview 2 | 3 | 1. Containers & Containers Adaptors 4 | 2. Iterators 5 | 3. Algorithms 6 | 4. Functors/Lambdas 7 | 8 | ## I. Containers 9 | 10 | ### Sequence Container 11 | 12 | > provide access to sequences of elements 13 | 14 | - **vector**: represents a sequence of elements of any type 15 | 16 | - out of bound exeception 17 | 18 | - ```cpp 19 | vector ints; 20 | ints.push_back(1); 21 | ints.push_back(2); 22 | ints << ints.at(2) << endl; // will throw std::out_of_range exception 23 | ints << ints[2] << endl; // does not through exception (undefined behaviours) 24 | ``` 25 | 26 | - Q: why does not vector bounds check by default? 27 | 28 | A: If you write your program correctly, bounds checking will just slow your code down. 29 | 30 | - **deque**: a double ended queue 31 | 32 | - push_front(): O(1) 33 | - pop_front(): O(1) 34 | - Element accessing (slow, as a trade-off) 35 | 36 | - **list** 37 | 38 | - **array** 39 | 40 | - **forward_list** 41 | 42 | ### Container Adaptors 43 | 44 | - **stacks**: Just a vector/deque to only allow push_back and pop_back + only allow access to top element 45 | - **queue**: Just the deque to only allow push_back and pop_front + only allow access to top element 46 | 47 | ### Associative Container 48 | 49 | > - have no idea of a sequence 50 | > 51 | > - data is accessed using the **key** instead of indexes 52 | 53 | - **Based on orderiing property of keys**. keys need to be comparable using ```<``` 54 | 55 | *faster to iterate thjrough a range or elements* 56 | 57 | - **map** 58 | 59 | - **set** 60 | 61 | - **Based on hash function.** Need to define how to hash the key 62 | 63 | *faster to access individual elements by keys.* 64 | 65 | - **unordered_map** 66 | 67 | - **unordered_set** 68 | 69 | - **Operation**: 70 | 71 | - ```map[key]```: if not found the key, will default initialize it **[map only]** 72 | 73 | - ```map.get(key)```: return an error if key not found **[map only]** 74 | 75 | - ```map.count(key)```: return 0 or 1 (used to find the key) **[map only]** 76 | 77 | - ```map.contains(key)```: C++ 20 **[map only]** 78 | 79 | 80 | 81 | ## II. Iterators 82 | 83 | > iterators allow iteration over any container whether it is ordered or not 84 | 85 | - **usage** 86 | 87 | - Create Iterator: ```set::iterator itr = mySet.begin();``` 88 | 89 | - Check the end: ```set::iterator itr = mySet.end();``` 90 | 91 | - Advance Iterator: ```itr++;``` 92 | 93 | - Dereference Iterator: ```*itr;``` 94 | 95 | 96 | 97 | ## III. Advanced Containers 98 | 99 | -------------------------------------------------------------------------------- /cpp/CoureMap.md: -------------------------------------------------------------------------------- 1 | Courses Map 2 | 3 | - **[C++]** Standfor CS106L: Standard C++ Programming (https://learncs.me/stanford/cs106l) 4 | 5 | - **[Linux]** UCB: Sysadmin DeCal (https://csdiy.wiki/编程入门/DeCal/) 6 | - **[Computer System | C ]** CMU CS15213: CSAPP 7 | - **[Operating System | C ]** MIT 6.S081: Operating System Engineering (https://csdiy.wiki/操作系统/MIT6.S081/) 8 | - **[Computer Network | C++ ]** Stdnford CS144: Computer Network(https://csdiy.wiki/计算机网络/CS144/#_1) 9 | - **[Database | C++]** CMU 15-445: Database Systems (https://csdiy.wiki/数据库系统/15445/) 10 | - **[Parallel Computing | C++ ]** CMU 15-418/Stanford CS149: Parallel Computing (https://csdiy.wiki/并行与分布式系统/CS149/) 11 | 12 | - **[Computer Architecture | C]** Princeton -------------------------------------------------------------------------------- /cpp/I-II-Stream.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### I. Purpose of Streams 4 | 5 | - **A stream** is an abstraction for input/output (a source/input or destination/output of characters of indefinite length) 6 | - **Types inserted into stream objects**: 7 | - any primitive type can be inserted into a stream 8 | - other types miust be explicityly tell 9 | - **Implementation** 10 | - Input from user is in text form (string) 11 | - Output to user is in text form (string) 12 | 13 | ### II. Output Streams 14 | 15 | - **output streams**: can only recieve data 16 | 17 | - All output streams are of type ```std::ostream``` 18 | - ```std::cout``` an example of output stream 19 | - ```std::ofstream``` send the data to a file 20 | 21 | - Sending data: 22 | - sending data using stream insertiong operation: ```<<``` 23 | - Insertion converts data to string and sends to stream 24 | 25 | - **Examples** 26 | 27 | ```cpp 28 | using std::cout; 29 | using std::endl; 30 | using std::string; 31 | 32 | void writeToStream(std::ostream& anyOutputStream, int favouriteNumber) { 33 | anyOutputStream << "Writing to stream: " 34 | << favouriteNumber << endl; 35 | } 36 | 37 | int main() { 38 | // Write an int to the user's console. 39 | int favouriteNumber = 1729; 40 | cout << "Result when writing an int directly to cout: " << favouriteNumber << endl; 41 | 42 | // Write an int to a file. 43 | std::ofstream outputFile("out.txt"); 44 | outputFile << "Result when writing an int to file: " << favouriteNumber << endl; 45 | 46 | // Write method to take any ostream 47 | std::ofstream fileOut("out.txt"); 48 | 49 | writeToStream(cout, favouriteNumber); 50 | writeToStream(fileOut, favouriteNumber + 1); 51 | return 0; 52 | } 53 | ``` 54 | 55 | 1. **Output to Console (stdout)**: 56 | - "Result when writing an int directly to cout: 1729" 57 | - "Writing to stream: 1729" 58 | 2. **Output to File ("out.txt")**: 59 | - "Writing to stream: 1730" 60 | 61 | ### III. Input Streams 62 | 63 | - **Can only give you data**: Extraction gets data from stream as a string and converts it into the appropriate type. 64 | 65 | - Pull out data using stream extraction operator: ```>>``` 66 | 67 | - **all input streams are of type ```std::istream```** 68 | 69 | - ```std::cin``` stream is an exeample of an inpit stream 70 | - read data from a file using a ```std::ifstream``` 71 | 72 | - **Data Extraction from Stream:** 73 | 74 | - Interger Extraction: 75 | 76 | - Extracting an integer will read as many characters as possible from the stream till the while space 77 | 78 | - String Extraction: 79 | 80 | - Read a single string: using ```>>``` will read a single word 81 | 82 | - To read a whole line, use 83 | 84 | ```cpp 85 | getline(istream& stream, string& line); 86 | ``` 87 | 88 | - Other methods for using streams 89 | 90 | ```cpp 91 | input.get(ch); // reads one char at a time 92 | input.close(); // closes stream 93 | input.clear(); // resets any fail bits 94 | input.open("filename"); // open stream on file 95 | input.seekg(0); // rewinds stream to start 96 | ``` 97 | 98 | 99 | 100 | ### IV. System 101 | 102 | - **Buffers** 103 | 104 | - The internal sequence of data stored in a stream is called a buffer.: 105 | 106 | - Istreams use them to store data we haven’t used yet 107 | 108 | - Ostreams use them to store data they haven’t passed along yet. 109 | 110 | - If we want to force the contents of the buffer to their destination, we can flush the stream: 111 | 112 | - ```cpp 113 | stream.flush(ch); // use by default 114 | stream << std::flush; // use if you are printing 115 | stream << std::endl; // use if you want a newline 116 | // This is equivalent to stream << "\n" << std::flush; 117 | ``` 118 | 119 | - Not all streams are buffered (std::cerr is an example). 120 | 121 | - **Stream bits** (Streams have four bits to give us information about their state): 122 | 123 | - Types 124 | - Good bit: No errors, the stream is good to go 125 | - EOF bit: End-of-file was reached during a previous operation 126 | - Fail Bit: Logical error on a previous operation 127 | - Bad bit: Likely unrecoverable error on previous operation 128 | 129 | - Check: 130 | 131 | ```cpp 132 | while(true) { stream >> temp; 133 | if(!stream) break; // checks fail or bad bit 134 | do_something(temp); 135 | } 136 | 137 | // simplified version 138 | while(stream >> temp) { 139 | do_something(temp); 140 | } 141 | 142 | // getline 143 | while(getline(stream, temp)) { 144 | do_something(temp); 145 | } 146 | ``` 147 | 148 | 149 | 150 | - **Operators** (The << and >> operators are functions!) 151 | 152 | ```cpp 153 | std::cout << "hello"; 154 | operator<<(std::cout, "hello"); 155 | ``` 156 | 157 | - The << and >> operators return the stream passed as their left argument. 158 | 159 | ```c pp 160 | (((std::cout << "hello") << 23) << "world"); 161 | ``` 162 | 163 | 164 | 165 | - **String Manipulator** (Using these stream manipulators, you can control various aspects of input/output operations in C++, including formatting, precision, and padding) 166 | 167 | - Common Stream Manipulators 168 | 169 | - **endl**: Inserts a newline character and flushes the stream. 170 | - **ws**: Skips all whitespace until it finds another character. 171 | - **boolalpha**: Prints "true" and "false" for boolean values instead of numeric representations. 172 | 173 | - Numeric Stream Manipulators 174 | 175 | ```cpp 176 | std::cout << std::hex << 10; // prints a 177 | std::cout << std::oct << 10; // prints 12 178 | std::cout << std::dec << 10; // prints 10 179 | ``` 180 | 181 | - **hex**: Prints numbers in hex 182 | - **setprecision**: Adjusts the precision numbers print with. 183 | 184 | - Padding Stream Manipulators 185 | 186 | ```cpp 187 | #include 188 | std::cout << "[" << std::left << std::setfill('-') 189 | << std::setw(10) << "Hi" << "]" << std::endl; 190 | // output [Hi----------] 191 | ``` 192 | 193 | - **setw**: Pads output 194 | - **setfill**: Fills padding with characters 195 | 196 | 197 | 198 | ### V. stringstream 199 | 200 | - Motivation: want to treat a string like a stream 201 | 202 | ```cpp 203 | #include 204 | Std::string line = "137 2.718 Hello"; 205 | std::stringstream stream(line); 206 | 207 | int myInt; 208 | double myDouble; 209 | std::string myString; 210 | stream >> myInt >> myDouble >> myString; 211 | 212 | std::cout << myInt << std::endl; 213 | std::cout << myDouble << std::endl; 214 | std::cout << myString << std::endl; 215 | ``` 216 | 217 | - Converting between data types 218 | - Tokenizing a string -------------------------------------------------------------------------------- /learning_path/infra.md: -------------------------------------------------------------------------------- 1 | ## Language: Python, C, C++, Rust 2 | ## CNCF生态技术: docker, containerd, runc, kata containers, kubernetes等云原生技术栈 3 | - aws: cloud practitioner -> solution architect 4 | - **Kubernetes and Cloud Native Associate (KCNA):** [Certification Link](https://training.linuxfoundation.org/certification/kubernetes-cloud-native-associate/) 5 | 6 | ## Linux: 7 | - Linux Container 8 | - **CompTIA Linux+ (XK0-005)** 9 | 10 | ## Database: 11 | - Distributed Database (CMU - 15455) 12 | 13 | ## Distributed System 14 | - Distributed System (MIT Open Course) 15 | 16 | ## Network 17 | - Standford (Implement TCP/IP Stack) 18 | -------------------------------------------------------------------------------- /open-source/resources.md: -------------------------------------------------------------------------------- 1 | https://github.com/t9tio/open-source-jobs?tab=readme-ov-file 2 | --------------------------------------------------------------------------------