<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[muhandis software]]></title><description><![CDATA[A technical blog dedicated to modern backend development and core computer science principles.]]></description><link>https://muhandis.software</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 21:04:09 GMT</lastBuildDate><atom:link href="https://muhandis.software/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[A Comprehensive Guide to Types, Interfaces, Classes, and Abstract Classes in TypeScript]]></title><description><![CDATA[When working with TypeScript, one of the first hurdles developers face is understanding the differences between types, interfaces, abstract classes, and classes. At first glance, they all seem to overlap—each can describe shapes, enforce contracts, o...]]></description><link>https://muhandis.software/guide-to-types-interfaces-classes-and-abstract-classes-in-typescript</link><guid isPermaLink="true">https://muhandis.software/guide-to-types-interfaces-classes-and-abstract-classes-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[notes]]></category><dc:creator><![CDATA[Mahmoud Khedr]]></dc:creator><pubDate>Sun, 28 Sep 2025 15:28:22 GMT</pubDate><content:encoded><![CDATA[<p>When working with TypeScript, one of the first hurdles developers face is understanding the differences between <strong>types, interfaces, abstract classes, and classes</strong>. At first glance, they all seem to overlap—each can describe shapes, enforce contracts, or structure code. But under the hood, they serve very different purposes, with distinct rules for compile-time safety, runtime behavior, inheritance, and extensibility.</p>
<p>This article breaks down these four building blocks side by side. It starts with a quick comparison table for a high-level snapshot, then dives deeper into when and why you’d use each—complete with examples, pros and cons, and common pitfalls. By the end, you’ll have a clear mental model for choosing the right tool in different scenarios, whether you’re defining flexible data shapes, designing library APIs, or implementing real-world application logic.</p>
<h2 id="heading-quick-overview">Quick Overview</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Runtime Existence</td><td>Can Instantiate</td><td>Implementation</td><td>Multiple Inheritance/Extends</td><td>Extensibility</td><td>Common Pitfalls/Misconceptions</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Type</strong></td><td>No (erased at compile-time)</td><td>No</td><td>No (purely descriptive)</td><td>Yes (via intersections: <code>&amp;</code>)</td><td>Can be extended via intersections or unions</td><td>Often confused with interfaces; types can't be “implemented” by classes but can describe them.</td></tr>
<tr>
<td><strong>Interface</strong></td><td>No (erased at compile-time)</td><td>No</td><td>No (declares shape only)</td><td>Yes (classes can implement multiple; interfaces can extend multiple)</td><td>Supports declaration merging (e.g., multiple files can add to the same interface)</td><td>Better for object literals; avoids some type alias recursion issues in large projects.</td></tr>
<tr>
<td><strong>Abstract Class</strong></td><td>Yes (transpiles to JS class)</td><td>No (requires subclass)</td><td>Partial (mix of abstract and concrete methods/properties)</td><td>No (single <code>extends</code>, but can implement multiple interfaces)</td><td>Can be extended by subclasses; useful for enforced inheritance</td><td>Not truly “abstract” in JS runtime—subclasses must implement abstracts, but runtime checks are limited.</td></tr>
<tr>
<td><strong>Class</strong></td><td>Yes (transpiles to JS class or function)</td><td>Yes</td><td>Full (concrete methods/properties)</td><td>No (single <code>extends</code>, but can implement multiple interfaces)</td><td>Can extend one class and implement interfaces; supports decorators</td><td>Runtime behavior means they're heavier; use sparingly if pure types suffice.</td></tr>
</tbody>
</table>
</div><p>This table offers a quick overview, showing how TypeScript converts to JavaScript. For example, types and interfaces vanish at runtime, while classes remain.</p>
<h2 id="heading-when-to-use-each-with-details-and-examples">When to Use Each (With Details and Examples)</h2>
<h3 id="heading-types"><strong>Types</strong></h3>
<ul>
<li><p><strong>Details</strong>: Types are aliases for other types and excel at composing complex shapes using TypeScript's advanced features like mapped types, conditional types, and template literals. They're purely for type checking—no runtime impact. Use them when you need flexibility beyond simple objects, like for primitives, functions, or generics. They're also great for utility types (e.g., <code>Partial&lt;T&gt;</code>, <code>Readonly&lt;T&gt;</code> built into TypeScript).</p>
</li>
<li><p><strong>Pros</strong>: Highly composable; support for unions/intersections make them ideal for modeling variants or merging schemas.</p>
</li>
<li><p><strong>Cons</strong>: No declaration merging (unlike interfaces); can lead to recursion errors in deeply nested types.</p>
</li>
<li><p><strong>Examples</strong>:</p>
<ul>
<li><p>Unions for enums-like behavior:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">type</span> Status = <span class="hljs-string">"active"</span> | <span class="hljs-string">"inactive"</span> | <span class="hljs-string">"pending"</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setStatus</span>(<span class="hljs-params">s: Status</span>) </span>{ <span class="hljs-comment">/* ... */</span> }
  setStatus(<span class="hljs-string">"active"</span>); <span class="hljs-comment">// OK</span>
  setStatus(<span class="hljs-string">"deleted"</span>); <span class="hljs-comment">// Error: Type '"deleted"' is not assignable to type 'Status'</span>
</code></pre>
</li>
<li><p>Intersections for combining types:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">type</span> User = { id: <span class="hljs-built_in">number</span>; name: <span class="hljs-built_in">string</span> };
  <span class="hljs-keyword">type</span> Role = { role: <span class="hljs-string">"admin"</span> | <span class="hljs-string">"user"</span> };
  <span class="hljs-keyword">type</span> UserWithRole = User &amp; Role;
  <span class="hljs-keyword">const</span> admin: UserWithRole = { id: <span class="hljs-number">1</span>, name: <span class="hljs-string">"Alice"</span>, role: <span class="hljs-string">"admin"</span> }; <span class="hljs-comment">// OK</span>
</code></pre>
</li>
<li><p>Complex computed types:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">type</span> User = { id: <span class="hljs-built_in">number</span>; name: <span class="hljs-built_in">string</span> };

  <span class="hljs-keyword">type</span> Keys = <span class="hljs-string">"id"</span> | <span class="hljs-string">"name"</span>;
  <span class="hljs-keyword">type</span> MyPick&lt;T, K <span class="hljs-keyword">extends</span> keyof T&gt; = { [P <span class="hljs-keyword">in</span> K]: T[P] }; <span class="hljs-comment">// custom Pick utility</span>
  <span class="hljs-keyword">type</span> UserId = MyPick&lt;User, <span class="hljs-string">"id"</span>&gt;; <span class="hljs-comment">// { id: number }</span>
</code></pre>
</li>
<li><p>When to prefer over interfaces: For non-object shapes or when using conditionals (e.g., <code>type Result&lt;T&gt; = T extends string ? Uppercase&lt;T&gt; : T</code>).</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-interfaces"><strong>Interfaces</strong></h3>
<ul>
<li><p><strong>Details</strong>: Interfaces define contracts for objects, functions, or classes. They're extensible via “declaration merging,” where TypeScript automatically combines multiple declarations of the same interface (a unique advantage, especially in libraries or large codebases where modules can augment shared interfaces without conflicts). They generally perform better than types for object shapes due to TypeScript's caching mechanisms, which optimize repeated type checks in complex projects.</p>
</li>
<li><p><strong>Pros</strong>: Easier to extend/merge; classes can <code>implement</code> them; clearer error messages in some cases; performance edge for large object graphs.</p>
</li>
<li><p><strong>Cons</strong>: Limited to object-like shapes (no unions/intersections directly—use <code>extends</code> for similar effects).</p>
</li>
<li><p><strong>Examples</strong>:</p>
<ul>
<li><p>Object shapes:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">interface</span> Person {
    name: <span class="hljs-built_in">string</span>;
    age: <span class="hljs-built_in">number</span>;
  }
  <span class="hljs-keyword">const</span> alice: Person = { name: <span class="hljs-string">"Alice"</span>, age: <span class="hljs-number">30</span> }; <span class="hljs-comment">// OK</span>
</code></pre>
</li>
<li><p>Extensibility with declaration merging (e.g., in separate files):</p>
<pre><code class="lang-typescript">  <span class="hljs-comment">// file1.ts</span>
  <span class="hljs-keyword">interface</span> Window {
    customProp: <span class="hljs-built_in">string</span>;
  }
  <span class="hljs-comment">// file2.ts</span>
  <span class="hljs-keyword">interface</span> Window {
    anotherProp: <span class="hljs-built_in">number</span>;
  }
  <span class="hljs-comment">// Merged automatically: Window has both customProp and anotherProp</span>
</code></pre>
</li>
<li><p>API definitions:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">interface</span> ApiResponse {
    data: unknown;
    status: <span class="hljs-built_in">number</span>;
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>): <span class="hljs-title">ApiResponse</span> </span>{ <span class="hljs-comment">/* ... */</span> }
</code></pre>
</li>
<li><p>When to prefer over types: For public APIs or team collaboration, as merging allows additive changes without breaking code; also for better compile-time performance in object-heavy codebases.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-abstract-classes"><strong>Abstract Classes</strong></h3>
<ul>
<li><p><strong>Details</strong>: These provide a base for subclasses, allowing shared code (concrete methods/properties) while forcing subclasses to implement abstracts. They support constructors, private/protected members, and runtime state. Unlike interfaces, they exist at runtime, so they're useful for polymorphism in inheritance chains.</p>
</li>
<li><p><strong>Pros</strong>: Enforce structure with shared implementation; great for frameworks (e.g., Angular services).</p>
</li>
<li><p><strong>Cons</strong>: Single inheritance limits flexibility; can lead to deep hierarchies if overused (favor composition over inheritance).</p>
</li>
<li><p><strong>Examples</strong>:</p>
<ul>
<li><p>Shared implementation:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> Animal {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">protected</span> name: <span class="hljs-built_in">string</span></span>) {}
    <span class="hljs-keyword">abstract</span> makeSound(): <span class="hljs-built_in">void</span>; <span class="hljs-comment">// Must be implemented by subclasses</span>
    move() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is moving`</span>); } <span class="hljs-comment">// Concrete method</span>
  }
  <span class="hljs-keyword">class</span> Dog <span class="hljs-keyword">extends</span> Animal {
    makeSound() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Woof!"</span>); }
  }
  <span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">"Buddy"</span>);
  dog.move(); <span class="hljs-comment">// "Buddy is moving"</span>
  dog.makeSound(); <span class="hljs-comment">// "Woof!"</span>
  <span class="hljs-comment">// new Animal("Abstract"); // Error: Cannot create an instance of an abstract class</span>
</code></pre>
</li>
<li><p>Mix of abstract/concrete:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> Logger {
    <span class="hljs-keyword">abstract</span> log(message: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">void</span>;
    error(message: <span class="hljs-built_in">string</span>) { <span class="hljs-built_in">this</span>.log(<span class="hljs-string">`ERROR: <span class="hljs-subst">${message}</span>`</span>); } <span class="hljs-comment">// Uses abstract method</span>
  }
</code></pre>
</li>
<li><p>When to use: For families of related classes (e.g., shapes in a graphics library: <code>Circle</code> and <code>Square</code> extend <code>AbstractShape</code> with a shared <code>draw()</code> method).</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-classes"><strong>Classes</strong></h3>
<ul>
<li><p><strong>Details</strong>: Full-fledged objects with runtime behavior, including constructors, methods, getters/setters, and access modifiers (<code>public</code>, <code>private</code>, <code>protected</code>, <code>readonly</code>). These modifiers are a key differentiator from interfaces (which don't support them), enabling better encapsulation and control over member visibility/inheritability. Classes can extend one class and implement multiple interfaces. Use for anything that needs instantiation and state management.</p>
</li>
<li><p><strong>Pros</strong>: Encapsulation and polymorphism; integrates with JS ecosystem (e.g., prototypes); access modifiers prevent unintended access/mutation.</p>
</li>
<li><p><strong>Cons</strong>: Runtime overhead; not ideal for pure data shapes (use interfaces/types instead).</p>
</li>
<li><p><strong>Examples</strong>:</p>
<ul>
<li><p>Basic class with constructor and access modifiers:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">class</span> User {
    <span class="hljs-keyword">private</span> id: <span class="hljs-built_in">number</span>;
    <span class="hljs-keyword">readonly</span> createdAt: <span class="hljs-built_in">Date</span>;
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> name: <span class="hljs-built_in">string</span>, <span class="hljs-keyword">protected</span> email: <span class="hljs-built_in">string</span></span>) {
      <span class="hljs-built_in">this</span>.id = <span class="hljs-built_in">Math</span>.random(); <span class="hljs-comment">// Constructor logic</span>
      <span class="hljs-built_in">this</span>.createdAt = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(); <span class="hljs-comment">// Readonly: can't be reassigned</span>
    }
    greet() { <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>; }
  }
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"alice@example.com"</span>);
  <span class="hljs-built_in">console</span>.log(user.greet()); <span class="hljs-comment">// "Hello, Alice"</span>
  <span class="hljs-comment">// user.id; // Error: Property 'id' is private</span>
  <span class="hljs-comment">// user.createdAt = new Date(); // Error: Cannot assign to 'createdAt' because it is a read-only property</span>
</code></pre>
</li>
<li><p>Inheritance and interfaces:</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">interface</span> Printable { print(): <span class="hljs-built_in">void</span>; }
  <span class="hljs-keyword">class</span> MyDocument <span class="hljs-keyword">extends</span> User <span class="hljs-keyword">implements</span> Printable { <span class="hljs-comment">// Extends class, implements interface</span>
    print() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Printing..."</span>); }
  }
</code></pre>
</li>
<li><p>When to use: For services, models with logic (e.g., a <code>DatabaseConnection</code> class that manages connections).</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-key-mental-model">Key Mental Model</h2>
<ul>
<li><p><strong>Types</strong>: Like sticky notes labeling data—”this must look like X or Y.” They're declarative and flexible, ideal for functional programming styles where you compose types without runtime concerns.</p>
</li>
<li><p><strong>Interfaces</strong>: Like legal contracts specifying requirements—”you must provide these properties/methods.” They're about promises and compatibility, promoting loose coupling.</p>
</li>
<li><p><strong>Abstract Classes</strong>: Like half-built houses with foundations and some rooms finished—you add the rest. They bridge design (abstracts) and implementation (concretes), enforcing a family resemblance.</p>
</li>
<li><p><strong>Classes</strong>: Like fully constructed, livable houses—you move in and use them. They're about creating real objects with behavior and state.</p>
</li>
</ul>
<p>A key insight: Types/interfaces are for <em>structural typing</em> (duck typing: if it quacks like a duck...), while classes/abstract classes add <em>nominal</em> elements via inheritance. In practice, mix them—e.g., a class implements an interface described by a type.</p>
<h2 id="heading-best-practice-rule-of-thumb">Best Practice Rule of Thumb</h2>
<ol>
<li><p>Start with <strong>interfaces</strong> for object shapes—they're more idiomatic in TypeScript docs and ecosystems (e.g., React props), and generally perform better than types due to caching mechanisms.</p>
</li>
<li><p>Use <strong>types</strong> when interfaces can't handle it (unions, intersections)—or for quick aliases. But if performance matters in huge projects, interfaces might edge out due to caching in the compiler.</p>
</li>
<li><p>Use <strong>abstract classes</strong> when you need to share code between similar classes—but avoid if composition (e.g., via mixins or functions) suffices, to prevent brittle hierarchies.</p>
</li>
<li><p>Use <strong>classes</strong> for everything you actually want to create instances of—and leverage TypeScript features like parameter properties (e.g., <code>constructor(public name: string)</code>) for brevity, along with access modifiers for encapsulation.</p>
</li>
</ol>
<p>Additional tips:</p>
<ul>
<li><p><strong>Migration/Refactoring</strong>: If a class has no state/methods, refactor to an interface/type for lighter code.</p>
</li>
<li><p><strong>Generics</strong>: All support generics (e.g., <code>interface List&lt;T&gt;</code>, <code>type Pair&lt;T&gt; = [T, T]</code>, <code>abstract class Base&lt;T&gt;</code>).</p>
</li>
<li><p><strong>Common Mistake</strong>: Don't use classes for namespaces—use modules instead.</p>
</li>
<li><p><strong>Performance</strong>: For massive type unions, types might bloat compile times; profile if needed. Interfaces' declaration merging shines in extensible libraries.</p>
</li>
<li><p><strong>Ecosystem Fit</strong>: In libraries, provide interfaces for users to implement or extend.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Mastering the differences between types, interfaces, abstract classes, and classes is less about memorizing rules and more about knowing which tool best fits the problem at hand. Types and interfaces shine at compile-time, letting you model and validate shapes with zero runtime cost. Abstract classes and classes, on the other hand, bridge into JavaScript’s runtime world, giving you structure, encapsulation, and actual behavior.</p>
<p>The bottom line: let <strong>types/interfaces</strong> guide the shape of your data, and reach for <strong>abstract classes/classes</strong> when you need runtime behavior. With this mental model, you can choose with confidence—and focus on building great software instead of wrestling with the type system.</p>
]]></content:encoded></item><item><title><![CDATA[LeetCode Problem Solving: Remove Element and Combination Sum Techniques]]></title><description><![CDATA[This is my first article on my new blog. I have the habit of grinding DSA problems. I took a LeetCode assessment where I had to solve two problems: the Remove Element and Combination Sum problems. In this article, I will explain my thought process fo...]]></description><link>https://muhandis.software/leetcode-problem-solving-remove-element-and-combination-sum-techniques</link><guid isPermaLink="true">https://muhandis.software/leetcode-problem-solving-remove-element-and-combination-sum-techniques</guid><category><![CDATA[problem solving skills]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[C++]]></category><dc:creator><![CDATA[Mahmoud Khedr]]></dc:creator><pubDate>Wed, 17 Sep 2025 22:48:08 GMT</pubDate><content:encoded><![CDATA[<p>This is my first article on my new blog. I have the habit of grinding DSA problems. I took a LeetCode assessment where I had to solve two problems: the Remove Element and Combination Sum problems. In this article, I will explain my thought process for solving each one.</p>
<h2 id="heading-remove-element">Remove Element</h2>
<p>this is the problem statement</p>
<blockquote>
<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a target="_blank" href="https://en.wikipedia.org/wiki/In-place_algorithm"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in</em> <code>nums</code> <em>which are not equal to</em> <code>val</code>.</p>
<p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p>
<ul>
<li><p>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</p>
</li>
<li><p>Return <code>k</code>.</p>
</li>
</ul>
<p><strong>Custom Judge:</strong></p>
<p>The judge will test your solution with the following code:</p>
<pre><code class="lang-plaintext">int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i &lt; actualLength; i++) {
    assert nums[i] == expectedNums[i];
}
</code></pre>
<p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p>
<p><strong>Example 1:</strong></p>
<pre><code class="lang-plaintext">Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code class="lang-plaintext">Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
</code></pre>
<p><strong>Constraints:</strong></p>
<ul>
<li><p><code>0 &lt;= nums.length &lt;= 100</code></p>
</li>
<li><p><code>0 &lt;= nums[i] &lt;= 50</code></p>
</li>
<li><p><code>0 &lt;= val &lt;= 100</code></p>
</li>
</ul>
</blockquote>
<p>First, we need to define our constraints. We should remove the elements in place and are not allowed to create a new array. An easy solution is to use the built-in remove method in our programming language of choice. This will work since <code>nums.length</code> is just under 100 elements. However, if we scale it to 10^6, this approach will become very slow.</p>
<p>My solution is very simple: whenever you find an element equal to <code>val</code>, replace its value with another value from the rest of the array. If there are none left, stop and return the new length, which is our <code>k</code>. To achieve this, we will have a variable <code>p</code> whose job is to stay at the position of the last element that equals <code>val</code>. And that's it.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> {</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">removeElement</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; nums, <span class="hljs-keyword">int</span> val)</span> </span>{
        <span class="hljs-keyword">int</span> p=<span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i&lt;nums.size();i++){
            <span class="hljs-keyword">if</span>(nums[i]!=val){
                nums[p]=nums[i];
                p++;
            }
        }
        <span class="hljs-keyword">return</span> p;
    }
};
</code></pre>
<hr />
<h2 id="heading-combination-sum">Combination Sum</h2>
<p>this is the problem statement</p>
<blockquote>
<pre><code class="lang-cpp">,[<span class="hljs-number">7</span>]]
Explanation:
<span class="hljs-number">2</span> <span class="hljs-keyword">and</span> <span class="hljs-number">3</span> are candidates, <span class="hljs-keyword">and</span> <span class="hljs-number">2</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span> = <span class="hljs-number">7.</span> Note that <span class="hljs-number">2</span> can be used multiple times.
<span class="hljs-number">7</span> is a candidate, <span class="hljs-keyword">and</span> <span class="hljs-number">7</span> = <span class="hljs-number">7.</span>
These are the only two combinations.
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code class="lang-cpp">Input: candidates = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>], target = <span class="hljs-number">8</span>
Output: [[<span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-number">2</span>],[<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">3</span>],[<span class="hljs-number">3</span>,<span class="hljs-number">5</span>]]
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code class="lang-cpp">Input: candidates = [<span class="hljs-number">2</span>], target = <span class="hljs-number">1</span>
Output: []
</code></pre>
<p><strong>Constraints:</strong></p>
<ul>
<li><p><code>1 &lt;= candidates.length &lt;= 30</code></p>
</li>
<li><p><code>2 &lt;= candidates[i] &lt;= 40</code></p>
</li>
<li><p>All elements of <code>candidates</code> are <strong>distinct</strong>.</p>
</li>
<li><p><code>1 &lt;= target &lt;= 40</code></p>
</li>
</ul>
</blockquote>
<p>After solving over 2000 problems on different platforms, I've gained some helpful insights. One of them is that when the constraints are very low, like in this problem, a brute-force solution will work just fine. That's exactly what I did for this problem.</p>
<p>When solving this problem, I divided it into two parts. First, I needed to generate the combinations. Second, I had to find a way to ensure the uniqueness of these combinations. The first part was easy—a recursive function with a loop to generate all possibilities.</p>
<p>For the second part, I had two ideas. The easiest was to sort each combination list and insert it into a set. This method guarantees uniqueness and is universal, working 100% of the time. However, if we read our constraints carefully, we see that all elements of <code>candidates</code> are <strong>distinct</strong>. So, I decided to set a starting point for the loop with each new recursive call. This was sufficient, and it's the role of the parameter <code>i</code> in the <code>helper</code> function.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> {</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">helper</span><span class="hljs-params">(<span class="hljs-keyword">int</span> i,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; candidates,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; <span class="hljs-built_in">list</span>,<span class="hljs-keyword">int</span> target,<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;&amp;ans)</span></span>{
        <span class="hljs-keyword">if</span>(target==<span class="hljs-number">0</span>){
            ans.push_back(<span class="hljs-built_in">list</span>);
            <span class="hljs-keyword">return</span>;
        }
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> j=i;j&lt;candidates.size();j++){
            <span class="hljs-keyword">if</span>(target-candidates[j]&gt;=<span class="hljs-number">0</span>){
                <span class="hljs-built_in">list</span>.push_back(candidates[j]);
                helper(j,candidates,<span class="hljs-built_in">list</span>,target-candidates[j],ans);
                <span class="hljs-built_in">list</span>.pop_back();
            }
        }
    }
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt; <span class="hljs-title">combinationSum</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&amp; candidates, <span class="hljs-keyword">int</span> target)</span> </span>{
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;&gt;ans;
        <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt;<span class="hljs-built_in">list</span>;
        helper(<span class="hljs-number">0</span>,candidates,<span class="hljs-built_in">list</span>,target,ans);
        <span class="hljs-keyword">return</span> ans;
    }
};
</code></pre>
<p>Thank you for reading my solutions. If you have any suggestions, please share them in the comments.</p>
]]></content:encoded></item></channel></rss>