<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Khan Muhammad Rifat on Medium]]></title>
        <description><![CDATA[Stories by Khan Muhammad Rifat on Medium]]></description>
        <link>https://medium.com/@khan1203?source=rss-5e1fd8fe5366------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pKR0-o17yXnYfWKBvj79dw.png</url>
            <title>Stories by Khan Muhammad Rifat on Medium</title>
            <link>https://medium.com/@khan1203?source=rss-5e1fd8fe5366------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:10:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khan1203/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Sliding Window Technique: A Powerful Approach to String and Array Problems]]></title>
            <link>https://medium.com/@khan1203/sliding-window-technique-a-powerful-approach-to-string-and-array-problems-c120f862a6bf?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/c120f862a6bf</guid>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[string-manipulation]]></category>
            <category><![CDATA[sliding-windows]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 09:32:22 GMT</pubDate>
            <atom:updated>2024-12-19T14:07:56.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ErdCfJ8VLpwPdNMiJDg93Q.png" /></figure><h3>Why do I need this technique?</h3><blockquote><strong>Reason is that</strong>: The sliding window technique effectively reduces time complexity from <em>O</em>(<em>n²</em>) → O(n), making it suitable for large datasets.</blockquote><p>The sliding window technique is a powerful algorithmic paradigm often employed to efficiently solve problems involving subarrays or substrings of a given sequence. It works by maintaining a “window” of a specific size that slides over the sequence, dynamically adjusting its boundaries to fulfill the problem’s constraints.</p><h3><strong><em>[^_^] </em>Core Concept</strong></h3><p>The essence of the sliding window technique lies in these key steps:</p><ol><li><strong>Initialization:</strong> Begin with a window of a certain size (which may be fixed or variable).</li><li><strong>Sliding:</strong></li></ol><ul><li><strong>Expand the window:</strong> Move the right boundary of the window to the right.</li><li><strong>Check for conditions:</strong> If the current window satisfies the problem’s requirements, update the result (e.g., maximum sum, minimum length, etc.).</li><li><strong>Shrink the window:</strong> Move the left boundary of the window to the right to maintain the desired window size or to meet the constraints.</li></ul><p><strong>3. Repeat:</strong> Continue this process of expanding, checking, and shrinking the window until it reaches the end of the sequence.</p><h3><strong><em>[^_^] </em>Types of Sliding Windows</strong></h3><ol><li><strong>Fixed-Size Window:</strong></li></ol><ul><li>The window size remains constant throughout the algorithm.</li><li>Example: Finding the maximum sum of a subarray of size ‘’.</li></ul><p><strong>2. Variable-Size Window:</strong></p><ul><li>The window size can dynamically change based on the problem’s constraints.</li><li>Example: Finding the minimum window substring in a string that contains all characters of another string.</li></ul><h3><strong><em>[^_^] </em>Applications</strong></h3><p>The sliding window technique finds applications in a wide range of problems, including:</p><h4><strong>String Manipulation:</strong></h4><ul><li>Finding the longest substring with at most ‘k’ distinct characters.</li><li>Finding the minimum window substring containing all characters of another string.</li><li>String matching and pattern recognition.</li></ul><h4><strong>Array Processing:</strong></h4><ul><li>Finding the maximum sum subarray of a given size.</li><li>Finding the longest subarray with a given sum.</li><li>Data stream analysis (e.g., finding the average of a moving window).</li></ul><h3><strong><em>[^_^] </em>Benefits</strong></h3><ul><li><strong>Efficiency:</strong> The sliding window technique often provides a more efficient solution than brute-force approaches, as it avoids unnecessary re-computations.</li><li><strong>Conciseness:</strong> The code for sliding window solutions can be relatively concise and elegant.</li></ul><h3><strong><em>[^_^] </em>Example</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*jGAH0Swwo5QGAy6Oa2EoFA.jpeg" /></figure><h4><strong>Fixed_Size Window:</strong></h4><p>Finding the maximum sum of a subarray of size ‘k’.</p><pre>int maxSumSubarray(vector&lt;int&gt;&amp; nums, int k) {<br>    int n = nums.size();<br>    if (n &lt; k) return 0; <br><br>    int sum = 0;<br>    for (int i = 0; i &lt; k; i++) {<br>        sum += nums[i];<br>    }<br><br>    int maxSum = sum;<br>    for (int i = k; i &lt; n; i++) {<br>        sum += nums[i] - nums[i - k]; // Slide the window<br>        maxSum = max(maxSum, sum);<br>    }<br><br>    return maxSum;<br>}</pre><h4>Step by Step:</h4><ol><li><strong>Initialize:</strong></li></ol><ul><li>n: Stores the size of the input array nums.</li><li>sum: Stores the sum of the current window.</li><li>maxSum: Stores the maximum sum of any subarray of size k encountered so far.</li></ul><p><strong>2. Slide the Window:</strong></p><ul><li><strong>Initial Window: </strong>The code initializes sum with the sum of the first k elements of the array. This represents the initial window of size k.</li><li><strong>Slide the Window:</strong></li><li>The for loop iterates from k to n-1. In each iteration:</li><li>sum += nums[i] - nums[i - k];: This line is the core of the sliding window technique.</li><li>nums[i]: Adds the next element to the window.</li><li>nums[i - k]: Subtracts the first element of the previous window. This effectively &quot;slides&quot; the window by one position to the right.</li><li>maxSum = max(maxSum, sum);: Updates maxSum if the current sum is greater than the previously recorded maximum.</li></ul><p><strong>3. Return Result:</strong></p><ul><li>After the loop completes, maxSum holds the maximum sum of any subarray of size k in the given array. The function returns maxSum.</li></ul><h4>Variable_Size Window:</h4><p>Longest Substring with at Most ‘k’ Distinct Characters.</p><pre>int longestSubstringKDistinct(string s, int k) {<br>    int n = s.length();<br>    if (n == 0 || k == 0) return 0;<br><br>    unordered_map&lt;char, int&gt; charCount;<br>    int left = 0, right = 0, maxLen = 0;<br><br>    while (right &lt; n) {<br>        charCount[s[right]]++;<br><br>        while (charCount.size() &gt; k) {<br>            charCount[s[left]]--;<br>            if (charCount[s[left]] == 0) {<br>                charCount.erase(s[left]);<br>            }<br>            left++;<br>        }<br><br>        maxLen = max(maxLen, right - left + 1);<br>        right++;<br>    }<br><br>    return maxLen;<br>}</pre><h4>Step by Step:</h4><ol><li><strong>Initialize:</strong></li></ol><ul><li>charCount: A hash map to store the count of each character in the current window.</li><li>left: The left pointer of the sliding window.</li><li>right: The right pointer of the sliding window.</li><li>maxLen: The length of the longest substring found so far.</li></ul><p><strong>2. Slide the Window:</strong></p><ul><li><strong>Expand:</strong> Move right to the right, adding the character at right to charCount.</li><li><strong>Check:</strong> If the number of distinct characters in charCount exceeds &#39;k&#39;:</li><li><strong>Shrink:</strong> Move left to the right until the number of distinct characters becomes &#39;k&#39; or less.</li><li>Remove characters from charCount as they are removed from the window.</li><li><strong>Update:</strong> If the current window size is greater than maxLen, update maxLen.</li></ul><p><strong>3. Return </strong><strong>maxLen:</strong> After the loop, maxLen will contain the length of the longest substring.</p><h3><strong><em>[^_^] </em>Conclusion</strong></h3><p>The sliding window technique is a valuable tool in the algorithmic arsenal. By understanding its core concepts and applications, you can effectively solve a wide range of string and array-related problems efficiently and elegantly.</p><p><strong>Note:</strong> This article provides a basic overview. There are many variations and optimizations of the sliding window technique, and mastering them requires practice and problem-solving experience.</p><p>Let’s connect on <a href="https://www.linkedin.com/in/khan1203/">Linkedin</a> 🚀<br>Follow <a href="http://medium.com/@khan1203">Khan Muhammad Rifat</a> for more resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c120f862a6bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Pathfinding: Mastering When to Use BFS, DFS, and Advanced Pathfinding Algorithms]]></title>
            <link>https://medium.com/@khan1203/the-art-of-pathfinding-mastering-when-to-use-bfs-dfs-and-advanced-pathfinding-algorithms-cb022395cce0?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb022395cce0</guid>
            <category><![CDATA[floyd-warshall]]></category>
            <category><![CDATA[bellman-ford-algorithm]]></category>
            <category><![CDATA[bfs-and-dfs]]></category>
            <category><![CDATA[shortest-path-algorithm]]></category>
            <category><![CDATA[path-printing-algorithms]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 09:25:03 GMT</pubDate>
            <atom:updated>2024-10-04T15:00:43.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F6TMU09iMer6MifM.png" /></figure><p>Understanding graph algorithms is crucial for solving various real-world problems efficiently. This blog explores five fundamental graph algorithms — BFS, DFS, Dijkstra’s Algorithm, Bellman-Ford Algorithm, and Floyd-Warshall Algorithm — highlighting their applications, strengths, and limitations.</p><h3>1. Breadth-First Search (BFS)</h3><h4><strong>When to Use:</strong></h4><p>BFS is optimal for traversing or searching through graphs, particularly when finding the shortest path in an <strong>unweighted</strong> graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*HemUsi3jrmf5WIP2uQEVeg.png" /><figcaption>taken from edureka.com</figcaption></figure><h4><strong>Why BFS is Useful:</strong></h4><ul><li>It guarantees the shortest path in unweighted graphs.</li><li>Applications include social network analysis (finding shortest connections) and GPS navigation for unweighted maps.</li><li>Utilized in flood-fill algorithms, common in graphics applications.</li></ul><h4><strong>Example Applications:</strong></h4><ul><li>Networking: Shortest path between computers.</li><li>Social Networks: Finding the shortest friendship chain.</li></ul><h4><strong>Limitations:</strong></h4><ul><li>Not suitable for weighted graphs, as it disregards edge weights, potentially leading to incorrect path calculations.</li></ul><h3>2. Depth-First Search (DFS)</h3><h4>When to Use:</h4><p>DFS is effective for exploring a graph deeply, making it suitable for problems like pathfinding, cycle detection, and topological sorting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*qD0N-G59QnWKg63w.png" /><figcaption>taken from freelancinggig.com</figcaption></figure><h4>Why DFS is Useful:</h4><ul><li>Ideal for exploring all possible paths or connected components.</li><li>Commonly used in cycle detection and solving puzzles requiring exhaustive exploration.</li></ul><h4>Example Applications:</h4><ul><li>Puzzle Solving: Navigating mazes or solving Sudoku.</li><li>Web Crawling: Exploring linked pages from a website.</li></ul><h4>Limitations:</h4><ul><li>Does not guarantee the shortest path; BFS or Dijkstra’s Algorithm is preferred for that purpose.</li><li>Can be inefficient for large graphs due to extensive path exploration.</li></ul><h3>3. Dijkstra’s Algorithm</h3><h4>When to Use:</h4><p>Dijkstra’s Algorithm excels at finding the shortest path from a source node to all other nodes in a graph with non-negative edge weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Xt3NHT5A02bf6YOzBismsQ.jpeg" /></figure><h4>Why Dijkstra is Useful:</h4><ul><li>Perfect for applications requiring shortest paths in weighted graphs, such as GPS systems, traffic management, and network routing.</li><li>More efficient than some alternatives when edge weights are non-negative.</li></ul><h4>Example Applications:</h4><ul><li>GPS Navigation: Determining the shortest route between locations.</li><li>Telecommunications: Optimizing data routing in networks.</li></ul><h4>Limitations:</h4><ul><li>Cannot handle negative edge weights; results may be incorrect if such weights exist in the graph.</li></ul><h3>4. Bellman-Ford Algorithm</h3><h4>When to Use:</h4><p>The Bellman-Ford algorithm is suitable for finding the shortest path in graphs that may contain negative weights, and it can also detect negative-weight cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*FU7yPRvzp-wwtSR2UjEQZg.jpeg" /></figure><h4>Why Bellman-Ford is Useful:</h4><ul><li>Handles negative edge weights, applicable in scenarios like financial arbitrage, where profitable loops may exist.</li><li>Essential for checking negative cycles, crucial in financial risk analysis.</li></ul><h4>Example Applications:</h4><ul><li>Currency Arbitrage: Identifying arbitrage opportunities through negative cycles.</li><li>Risk Management: Analyzing financial risks involving fluctuating costs.</li></ul><h4>Limitations:</h4><ul><li>Slower than Dijkstra’s Algorithm; less efficient for large graphs with non-negative weights.</li></ul><h3>5. Floyd-Warshall Algorithm</h3><h4>When to Use:</h4><p>Floyd-Warshall is designed to solve the all-pairs shortest path problem, effective on both positive and negative edge weights but failing with negative cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*X2r3q8KmBYcoQwLioJ1E7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*TpccmFjc5CIEm-vyGadiNA.png" /></figure><h4>Why Floyd-Warshall is Useful:</h4><ul><li>Computes shortest paths between all pairs of nodes, beneficial for dense graphs needing comprehensive evaluations.</li><li>Versatile across various applications requiring complete shortest-path matrices.</li></ul><h4>Example Applications:</h4><ul><li>Network Routing: Finding shortest paths between all servers.</li><li>Map Systems: Calculating paths between multiple points of interest.</li></ul><h4>Limitations:</h4><ul><li>Inefficient for sparse graphs due to higher time complexity compared to Dijkstra or Bellman-Ford.</li><li>Fails in the presence of negative cycles, leading to incorrect results.</li></ul><h3>Conclusion</h3><p>Selecting the appropriate graph algorithm hinges on the specific problem characteristics and graph types. A quick reference guide includes:</p><ul><li>Use BFS for unweighted graphs needing shortest paths.</li><li>Opt for DFS when exploring all paths or detecting cycles.</li><li>Choose Dijkstra’s Algorithm for weighted graphs without negative edges.</li><li>Apply the Bellman-Ford Algorithm when dealing with negative weights or detecting cycles.</li><li>Implement Floyd-Warshall Algorithm for comprehensive all-pairs shortest path calculations in dense graphs.</li></ul><p>By understanding these algorithms’ strengths and limitations, one can effectively address diverse challenges ranging from navigation systems to complex logistical operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb022395cce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BFS Breakdown for Beginners: A Powerful Tool for Graph Algorithms]]></title>
            <link>https://medium.com/@khan1203/bfs-breakdown-for-beginners-a-powerful-tool-for-graph-algorithms-6923ca1eac1d?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/6923ca1eac1d</guid>
            <category><![CDATA[bfs-and-dfs]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[graph-traversal]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 05:53:05 GMT</pubDate>
            <atom:updated>2024-09-18T16:50:33.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*CxCGcJ__SXz9mIlG.png" /><figcaption>Taken from random online image</figcaption></figure><h3>Introduction</h3><p>The <strong>Breadth-First Search (BFS)</strong> algorithm is one of the simplest and most widely used algorithms in computer science. It’s a way to explore nodes in a graph, visiting all the nodes at the present depth before moving on to nodes at the next depth level. BFS is a fundamental technique used for solving problems such as finding the shortest path in unweighted graphs, traversing mazes, and more.</p><p>In this guide, we’ll break down how BFS works, provide real-life examples to make it more relatable, and guide you through the process of writing BFS in pseudocode and real code.</p><h3><strong>What is BFS?</strong></h3><p>Breadth-First Search (BFS) is a graph traversal algorithm that explores all vertices in a graph level by level. It starts from a given source vertex and visits all its neighbors before moving on to their neighbors. This process continues until all vertices have been visited.</p><h3>Real-Life Analogy</h3><p>Let’s consider a simple real-world example to help understand BFS.</p><p><strong>Finding the Shortest Route in a City:</strong></p><p>Imagine you’re in a city where each intersection is a node, and each street connecting two intersections is an edge. You are standing at intersection A, and you want to reach intersection X. But you want to find the shortest route.</p><p>You might start by checking all the intersections (nodes) connected directly to intersection A. Once you’ve done that, you check the intersections that are two streets away, then three streets away, and so on. You’ll find the shortest route by exploring all possible routes layer by layer. This is exactly what BFS does.</p><h3>Key Characteristics of BFS:</h3><ul><li><strong>Traversal Type:</strong> Level-by-level (or layer-by-layer).</li><li><strong>Data Structure Used:</strong> Queue (First In, First Out — FIFO).</li><li><strong>Time Complexity:</strong> O(V + E), where V is the number of vertices and E is the number of edges.</li><li><strong>Space Complexity:</strong> O(V), as it stores vertices in the queue.</li><li><strong>Applicable To:</strong> Both graphs and trees.</li></ul><h3>How BFS Works</h3><p>BFS uses a <strong>queue</strong> to store nodes to be explored and a <strong>visited list</strong> to ensure nodes aren’t visited multiple times. Here are the steps:</p><ol><li><strong>Initialize</strong>: Start from the root node (or any arbitrary node in a graph), mark it as visited, and enqueue it.</li><li><strong>Dequeue and Explore</strong>: Dequeue the front node from the queue and explore its neighbors (all nodes connected by an edge).</li><li><strong>Enqueue Neighbors</strong>: For each unvisited neighbor, mark it as visited and add it to the queue.</li><li><strong>Repeat</strong>: Repeat the process until the queue is empty.</li></ol><h3>Pseudocode for BFS</h3><p>Here’s a simple step-by-step pseudocode for BFS:</p><pre>BFS(Graph, start_node):<br>    Create a queue Q<br>    Create a set visited to track visited nodes<br>    Enqueue start_node in Q and mark it as visited<br>    <br>    while Q is not empty:<br>        current_node = Q.dequeue()  # Get the front node from the queue<br>        process(current_node)       # Process the node (e.g., print it)<br>        <br>        for each neighbor of current_node:<br>            if neighbor is not visited:<br>                Enqueue neighbor in Q<br>                Mark neighbor as visited</pre><h3>Step-by-step Visual Representation of BFS:</h3><p><strong><em>Step1: </em></strong><em>Initially queue and visited arrays are empty.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*XSeK81zmKhKEhRGU.png" /><figcaption>all pictures taken from geeks-for-geeks</figcaption></figure><p><strong><em>Step2: </em></strong><em>Push 0 into queue and mark it visited.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Oo_AyiVHkMeoVgHe.png" /></figure><p><strong><em>Step 3: </em></strong><em>Remove 0 from the front of queue and visit the unvisited neighbours and push them into queue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*hJSK7TB15DwRKBgI.png" /></figure><p><strong><em>Step 4: </em></strong><em>Remove node 1 from the front of queue and visit the unvisited neighbours and push them into queue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*yFO2ol1T-WIOh0le.png" /></figure><p><strong><em>Step 5: </em></strong><em>Remove node 2 from the front of queue and visit the unvisited neighbours and push them into queue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*RpzIW71Hu46F6wOp.png" /></figure><p><strong><em>Step 6: </em></strong><em>Remove node 3 from the front of queue and visit the unvisited neighbours and push them into queue. As we can see that every neighbours of node 3 is visited, so move to the next node that are in the front of the queue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*oXGPKzQFnrKJUalR.png" /></figure><p><strong><em>Steps 7: </em></strong><em>Remove node 4 from the front of queue and visit the unvisited neighbours and push them into queue. As we can see that every neighbours of node 4 are visited, so move to the next node that is in the front of the queue.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*1l0RuLFt0kUz_5Qj.png" /></figure><p><em>Now, Queue becomes empty, So, terminate these process of iteration.</em></p><h3>BFS Implementation</h3><p>For those more comfortable with<strong><em> C++</em></strong>, here’s how BFS can be implemented:</p><pre>#include &lt;iostream&gt;<br>#include &lt;queue&gt;<br>#include &lt;vector&gt;<br><br>using namespace std;<br><br>void BFS(vector&lt;vector&lt;int&gt;&gt;&amp; graph, int start) {<br>    int n = graph.size();   //Initialize size of graph(numbe of rows)<br>    //Initialize a boolian vector for tracking visited nodes<br>    vector&lt;bool&gt; visited(n, false);<br>    queue&lt;int&gt; q; // initialize a queue<br><br>    // Mark the starting vertex as visited and enqueue it<br>    visited[start] = true;<br>    q.push(start);<br><br>    // While the queue is not empty<br>    while (!q.empty()) {<br>        // Dequeue the front node<br>        int current = q.front();<br>        q.pop();<br><br>        // Process the current node (e.g., print it)<br>        cout &lt;&lt; current &lt;&lt; &quot; &quot;;<br><br>        // Iterate over the neighbors of the current node<br>        for (int neighbor : graph[current]) {<br>            // If the neighbor is not visited<br>            if (!visited[neighbor]) {<br>                // Mark the neighbor as visited and enqueue it<br>                visited[neighbor] = true;<br>                q.push(neighbor);<br>            }<br>        }<br>    }<br>}<br><br>int main() {<br>    int n, m;<br>    cin &gt;&gt; n &gt;&gt; m;<br><br>    // Create an adjacency list representation of the graph<br>    vector&lt;vector&lt;int&gt;&gt; graph(n);<br><br>    // Read and add edges to the graph<br>    for (int i = 0; i &lt; m; i++) {<br>        int u, v;<br>        cin &gt;&gt; u &gt;&gt; v;<br>        graph[u].push_back(v);<br>        graph[v].push_back(u); // For undirected graphs<br>    }<br><br>    int start;<br>    cin &gt;&gt; start;<br><br>    // Perform BFS starting from the given vertex<br>    BFS(graph, start);<br><br>    return 0;<br>}</pre><p>For those more comfortable with <strong>Python</strong>, here’s how BFS can be implemented:</p><pre>from collections import deque<br><br>def BFS(graph, start):<br>    &quot;&quot;&quot;Performs Breadth-First Search (BFS) on a graph.<br><br>    Args:<br>        graph: A dictionary representing the graph, where keys are nodes and values are lists of their neighbors.<br>        start: The starting node for the BFS traversal.<br><br>    Returns:<br>        A list of nodes in the order they were visited.<br>    &quot;&quot;&quot;<br><br>    visited = set()  # Set to keep track of visited nodes<br>    queue = deque([start])  # Queue to store nodes to be visited<br><br>    while queue:<br>        node = queue.popleft()<br>        if node not in visited:<br>            visited.add(node)<br>            queue.extend(neighbor for neighbor in graph[node] if neighbor not in visited)<br><br>    return list(visited)<br><br># Example usage:<br>graph = {<br>    &#39;A&#39;: [&#39;B&#39;, &#39;C&#39;],<br>    &#39;B&#39;: [&#39;D&#39;, &#39;E&#39;],<br>    &#39;C&#39;: [&#39;F&#39;],<br>    &#39;D&#39;: [],<br>    &#39;E&#39;: [&#39;F&#39;],<br>    &#39;F&#39;: []<br>}<br><br>start_node = &#39;A&#39;<br>result = BFS(graph, start_node)<br>print(result)  # Output: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;]</pre><h3>Applications of BFS</h3><p>BFS is used in a wide variety of real-world and computational problems:</p><ol><li><strong>Finding the Shortest Path</strong>: In unweighted graphs, BFS can be used to find the shortest path between two nodes.</li><li><strong>Social Networks</strong>: Finding people within a certain degree of connection (e.g., 2nd-degree friends).</li><li><strong>Web Crawlers</strong>: BFS is used to explore web pages linked to a given page.</li><li><strong>Solving Mazes</strong>: BFS explores paths layer by layer, which is useful in finding the shortest path out of a maze.</li><li><strong>Finding Connected Components</strong>: In graph theory, BFS helps in identifying all components of a graph.</li></ol><h3>Side Effects of BFS and their possible Alternatives</h3><h4>1. High Memory Usage</h4><ul><li><strong>Side Effect</strong>: BFS requires storing all nodes at the current depth level in a queue, which can lead to high memory consumption, especially in large or dense graphs.</li><li><strong>Alternative</strong>: <strong>Depth-First Search (DFS)</strong> uses less memory as it explores one path deeply at a time, storing fewer nodes simultaneously.</li></ul><h4>2. Not Suitable for Weighted Graphs</h4><ul><li><strong>Side Effect</strong>: BFS treats all edges as having the same weight, making it unsuitable for graphs with weighted edges.</li><li><strong>Alternative</strong>: <strong>Dijkstra’s Algorithm</strong> handles graphs with weighted edges and finds the shortest path based on edge weights.</li></ul><h4>3. Inefficient for Deep or Infinite Graphs</h4><ul><li><strong>Side Effect</strong>: BFS explores all nodes layer by layer, which is inefficient for deep graphs or infinite state spaces.</li><li><strong>Alternative</strong>: <strong>Depth-Limited Search (DLS)</strong> or <strong>Iterative Deepening DFS (IDDFS)</strong> explores nodes to a limited depth, making it more efficient for deep or infinite graphs.</li></ul><h4>4. Overhead of Tracking Visited Nodes</h4><ul><li><strong>Side Effect</strong>: BFS requires maintaining a visited set, leading to memory overhead, especially in sparse graphs.</li><li><strong>Alternative</strong>: <strong>Bidirectional Search</strong> reduces the search space by searching from both the start and goal simultaneously, lowering memory usage.</li></ul><h4>5. Slow for Complex or Large Graphs</h4><ul><li><strong>Side Effect</strong>: BFS can be slow when traversing large graphs as it explores all possible nodes at each level before moving deeper.</li><li><strong>Alternative</strong>: <strong>A*</strong> Search is faster for complex graphs, as it uses a heuristic to prioritize nodes closer to the goal, reducing unnecessary exploration.</li></ul><h4>6. Not Ideal for Backtracking or Puzzle-Solving</h4><ul><li><strong>Side Effect</strong>: BFS is inefficient for problems that require exploring deep paths or backtracking, as it checks all nodes level by level.</li><li><strong>Alternative</strong>: <strong>DFS</strong> or <strong>Backtracking Algorithms</strong> are more suitable for puzzle-solving and scenarios where deep exploration is prioritized over breadth.</li></ul><p>— — — —</p><blockquote>Follow <a href="https://medium.com/@khan1203">Khan Muhammad Rifat</a> for more resources.<br>Let’s connect on <a href="https://www.linkedin.com/in/khan1203/">Linkedin</a>.</blockquote><p>— — — —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6923ca1eac1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compile-Time Choice vs. Runtime Surprise: Demystifying Binding in C++]]></title>
            <link>https://towardsdev.com/compile-time-choice-vs-runtime-surprise-demystifying-binding-in-c-e785580f696a?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/e785580f696a</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[compile-times]]></category>
            <category><![CDATA[runtime-environment]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 10:31:28 GMT</pubDate>
            <atom:updated>2024-07-09T17:04:30.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dd9C4NgUPZm5uKjacq2yAg.jpeg" /></figure><p>In the world of programming, especially in C++, the concepts of static binding and dynamic binding play a crucial role in how programs operate and perform. This blog will delve into these concepts, highlighting their differences, problems, solutions, and practical applications with code snippets to illustrate the ideas.</p><p>Let’s get connected on <a href="https://www.linkedin.com/in/khan1203/">Linkedin</a> for more resource and networks for FREE</p><h4>What’s the Deal with Binding?</h4><p>Binding in programming refers to the association of a function call with the function definition. It is the process of linking a procedure call to the code to be executed in response to the call.</p><p>In simpler terms, binding refers to the process of establishing a connection between a function call and its corresponding definition. It’s akin to a handshake — ensuring the correct function is invoked when its name is mentioned.</p><h3>Static Binding: The Compile-Time Champion</h3><p>Static binding, also known as <strong><em>early binding</em></strong>, makes its decision at compile time. The compiler, with its eagle-eyed scrutiny, determines the exact method to be called based on the declared object type. This binding approach shines in scenarios where function behavior remains static throughout the program’s execution.</p><p>It is typically used with overloaded methods and private, static, and final methods as mentioned :</p><h4>Examples of Static Binding</h4><ol><li><strong>Overloaded Methods</strong></li></ol><pre>//Overloaded Method:<br>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Example {<br>public:<br>    void display(int i) {<br>        cout &lt;&lt; &quot;Display with int: &quot; &lt;&lt; i &lt;&lt; endl;<br>    }<br><br>    void display(double d) {<br>        cout &lt;&lt; &quot;Display with double: &quot; &lt;&lt; d &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Example ex;<br>    ex.display(10);     // Display with int: 10<br>    ex.display(10.5);   // Display with double: 10.5<br>    return 0;<br>}</pre><p><strong>2. Static Method</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Example {<br>public:<br>    static void display() {<br>        cout &lt;&lt; &quot;Static display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Example::display(); // Static display function called<br>    return 0;<br>}</pre><p><strong>3. Final Method</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    void display() final {<br>        cout &lt;&lt; &quot;Base display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Derived : public Base {<br>     void display() { // This will cause a compilation error<br>        cout &lt;&lt; &quot;Derived display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Derived d;<br>    d.display(); // Base display function called<br>    return 0;<br>}</pre><h3>Problems with Static Binding</h3><ol><li><strong>Lack of Flexibility</strong>: Since the function call is determined at compile time, the program lacks flexibility. It cannot change behavior at runtime based on object types.</li><li><strong>Code Duplication</strong>: Often requires multiple similar methods, leading to code duplication.</li><li><strong>Inheritance Issues</strong>: In scenarios involving inheritance, the base class version of a method is always called, even when a derived class object is used.</li></ol><h3>Solutions</h3><ol><li><strong>Use of Virtual Functions</strong>: To overcome the limitations of static binding, C++ provides virtual functions, which are used in dynamic binding.</li><li><strong>Template Functions</strong>: Utilizing templates can help in avoiding code duplication.</li></ol><h3>Dynamic Binding: The Runtime Master</h3><p>Dynamic binding, also known as<strong><em> late binding</em></strong>, waits until runtime to decide which function to call. This decision hinges on the actual object type at runtime, offering a degree of flexibility absent in static binding. It is achieved using virtual functions and pointers or references to base class objects.</p><h4>Examples of Dynamic Binding</h4><ol><li><em>Virtual Functions</em></li></ol><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    virtual void display() {<br>        cout &lt;&lt; &quot;Base display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Derived : public Base {<br>public:<br>    void display() override {<br>        cout &lt;&lt; &quot;Derived display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Base *bptr;<br>    Derived d;<br>    bptr = &amp;d;<br>    bptr-&gt;display(); // Derived display function called due to dynamic binding<br>    return 0;<br>}</pre><p><strong>2. Virtual Destructor</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    virtual ~Base() {<br>        cout &lt;&lt; &quot;Base destructor called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Derived : public Base {<br>public:<br>    ~Derived() {<br>        cout &lt;&lt; &quot;Derived destructor called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Base *bptr = new Derived();<br>    delete bptr; // Derived destructor called due to dynamic binding<br>    return 0;<br>}</pre><p><strong>3. Abstract Base Class</strong></p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>class Base {<br>public:<br>    virtual void display() = 0; // Pure virtual function<br>};<br><br>class Derived : public Base {<br>public:<br>    void display() override {<br>        cout &lt;&lt; &quot;Derived display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Base *bptr;<br>    Derived d;<br>    bptr = &amp;d;<br>    bptr-&gt;display(); // Derived display function called due to dynamic binding<br>    return 0;<br>}</pre><h3>Advantages of Dynamic Binding</h3><ol><li><strong>Flexibility</strong>: Allows programs to decide which function to invoke at runtime, enhancing flexibility.</li><li><strong>Polymorphism</strong>: Supports runtime polymorphism, enabling one interface to be used for a general class of actions.</li><li><strong>Reduced Code Duplication</strong>: By using virtual functions, the need for multiple similar functions is minimized.</li></ol><h3>Problems with Dynamic Binding</h3><ol><li><strong>Performance Overhead</strong>: Slightly slower than static binding due to the additional overhead of determining the function to be called at runtime.</li><li><strong>Complexity</strong>: Introduces complexity in understanding and maintaining the code, especially for beginners.</li><li><strong>Memory Usage</strong>: Slightly increases memory usage due to the virtual table.</li></ol><blockquote>Why Do We Use the Virtual Function in Case of Dynamic Binding but Not in Case of Static Binding?</blockquote><h3>Virtual Function in Dynamic Binding</h3><p>In dynamic binding, virtual functions are used to achieve runtime polymorphism. When a function is declared as virtual in a base class, it can be overridden in derived classes. The decision of which function to call is made at runtime based on the actual object type that a base class pointer or reference points to. This allows the program to call the derived class’s function through a base class pointer, enabling flexible and dynamic behavior.</p><pre>class Base {<br>public:<br>    virtual void display() {<br>        cout &lt;&lt; &quot;Base display function called&quot; &lt;&lt; endl;<br>    }<br>};<br><br>class Derived : public Base {<br>public:<br>    void display() override {<br>        cout &lt;&lt; &quot;Derived display function called&quot; &lt;&lt; endl;<br>    }<br>};</pre><h3>Static Binding Does Not Require Virtual Functions</h3><p>In static binding, the method to be invoked is determined at compile time. Since the compiler already knows which method to call, there is no need for virtual functions. The function calls are straightforward and direct, resulting in better performance and simplicity. Static binding is typically used when the function behavior is not expected to change at runtime, and thus, the overhead of virtual functions is unnecessary.</p><pre>class Base {<br>public:<br>    void display() {<br>        cout &lt;&lt; &quot;Base display function called&quot; &lt;&lt; endl;<br>    }<br>};</pre><h3>Applications and Usage</h3><blockquote>Static Binding</blockquote><ul><li><strong>Compile-Time Efficiency</strong>: Programs where performance is critical and the call decision can be made at compile time.</li><li><strong>Embedded Systems</strong>: Where resources are limited and predictability is crucial.</li></ul><blockquote>Dynamic Binding</blockquote><ul><li><strong>GUI Applications</strong>: Where flexibility and extensibility are required.</li><li><strong>Plugin Architectures</strong>: Systems where new components might be added at runtime.</li><li><strong>Object-Oriented Programming</strong>: Scenarios where polymorphism is heavily used.</li></ul><h3>Which is Better?</h3><blockquote>The choice between static and dynamic binding depends on the application requirements. Static binding offers better performance and simplicity, making it ideal for systems where speed and resource constraints are critical. Dynamic binding, on the other hand, provides flexibility and extensibility, making it suitable for applications requiring runtime decision-making and polymorphism.</blockquote><h3>Conclusion</h3><p>Understanding the differences between static and dynamic binding, along with their respective advantages and disadvantages, is crucial for efficient C++ programming. While static binding provides performance benefits, dynamic binding offers flexibility and supports polymorphism. Choosing the right binding method based on the application requirements can lead to better program design and performance.</p><p>Follow <a href="https://medium.com/khan1203">Khan Muhammad Rifat</a> to get more resourceful blogs for FREE</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e785580f696a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/compile-time-choice-vs-runtime-surprise-demystifying-binding-in-c-e785580f696a">Compile-Time Choice vs. Runtime Surprise: Demystifying Binding in C++</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Powerhouse Duo: Classes vs. Interfaces in C++ OOP]]></title>
            <link>https://towardsdev.com/unveiling-the-powerhouse-duo-classes-vs-interfaces-in-c-oop-a237a06c0cad?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/a237a06c0cad</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Wed, 29 May 2024 07:11:17 GMT</pubDate>
            <atom:updated>2024-06-15T18:17:45.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-oriented programming (OOP) has been a cornerstone of software development for decades, and C++ is one of the most popular and versatile OOP languages. Two fundamental concepts in OOP are classes and interfaces. Although they share some similarities, they serve distinct purposes and have unique characteristics. In this blog post, we will explore the differences between classes and interfaces in C++, complete with examples and code snippets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UiOw5h3FtQhjpgOd" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Classes: The Blueprints for Objects</h3><p>Imagine a class as a detailed blueprint, meticulously outlining the characteristics (data members) and functionalities (member functions) that objects of a particular type will embody. It serves as a template, a master plan from which you can forge numerous objects, each inheriting the class’s defined attributes and behaviors.</p><p>In C++, a class is a user-defined data type that encapsulates data and functions that operate on that data into a single unit. Classes can have member variables, member functions, and constructors/destructors. They support inheritance, encapsulation, and polymorphism, which are the core principles of OOP.</p><p>Example of a Class with a simple code snippet:</p><pre>class Animal {<br>public:<br>    string name;<br>    int age;<br><br>    void makeSound() {<br>        cout &lt;&lt; &quot;Generic animal sound!&quot; &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Animal dog;<br>    dog.name = &quot;Fido&quot;;<br>    dog.age = 3;<br>    dog.makeSound(); // Output: Generic animal sound!<br>    return 0;<br>}</pre><p>In this example, the Animal class establishes a structure for objects representing animals. Each Animal object will have name and age data members, along with a makeSound() function (though its implementation here is generic).</p><p>Another Example of class:</p><pre>#include &lt;iostream&gt;<br><br>class Shape {<br>public:<br>    // Constructor<br>    Shape(string name) : name_(name) {}<br><br>    // Member function<br>    void draw() {<br>        cout &lt;&lt; &quot;Drawing &quot; &lt;&lt; name_ &lt;&lt; endl;<br>    }<br><br>private:<br>    string name_;<br>};<br><br>int main() {<br>    Shape square(&quot;Square&quot;);<br>    square.draw(); //Output: Drawing Square<br><br>    return 0;<br>}</pre><h3>Interfaces: Specifying Contracts, not Implementations</h3><p>Now, let’s shift our focus to interfaces. Unlike classes, interfaces don’t provide concrete implementations for member functions. Instead, they act as contracts, dictating the functionalities (method signatures with return types and parameter lists) that classes that adhere to the interface (implementing classes) must deliver. This fosters separation of concerns, ensuring that any class adhering to the interface can be seamlessly integrated into the program.</p><p>In C++, an interface is implemented using an abstract class. An abstract class is a class that has at least one pure virtual function. A pure virtual function is a function declared by assigning = 0 in its declaration. Abstract classes cannot be instantiated directly and are meant to be used as base classes.</p><p>Simple code snippet of Interfaces:</p><pre>class Drawable {<br>public:<br>    virtual void draw() = 0; // Pure virtual function (abstract method)<br>};<br><br>class Circle : public Drawable {<br>public:<br>    int radius;<br><br>    void draw() override {<br>        cout &lt;&lt; &quot;Drawing a circle with radius &quot; &lt;&lt; radius &lt;&lt; endl;<br>    }<br>};<br><br>int main() {<br>    Drawable* obj; // Can point to any object that implements Drawable<br>    Circle circle;<br>    circle.radius = 5;<br>    obj = &amp;circle; // Dynamic binding at runtime<br>    obj-&gt;draw(); // Output: Drawing a circle with radius 5<br>    return 0;<br>}</pre><p>Here, the Drawable interface mandates a pure virtual function, draw(), which any class implementing Drawable must define. The Circle class implements Drawable and provides its own specific implementation for draw(). Note the use of pointers and dynamic binding to allow objects of different classes that are implemented Drawable to be used interchangeably.</p><p>Another Important example of Interface:</p><pre>#include &lt;iostream&gt;<br><br>class Drawable {<br>public:<br>  virtual void draw() const = 0; // Pure virtual function makes Drawable abstract<br>};<br><br>class Circle : public Drawable {<br>private:<br>  double radius;<br><br>public:<br>  Circle(double radius) : radius(radius) {}<br><br>  void draw() const override {<br>    cout &lt;&lt; &quot;Drawing a circle with radius &quot; &lt;&lt; radius &lt;&lt; endl;<br>  }<br>};<br><br>class Triangle : public Drawable {<br>private:<br>  double base, height;<br><br>public:<br>  Triangle(double base, double height) : base(base), height(height) {}<br><br>  void draw() const override {<br>    cout &lt;&lt; &quot;Drawing a triangle with base &quot; &lt;&lt; base &lt;&lt; &quot; and height &quot; &lt;&lt; height &lt;&lt; endl;<br>  }<br>};<br><br>// Can only use references to the abstract class Drawable<br>void draw_shape(const Drawable&amp; shape) {<br>  shape.draw(); // Calls the specific draw method of the subclass through reference<br>}<br><br>int main() {<br>  Circle circle(5);<br>  Triangle triangle(4, 6);<br><br>  draw_shape(circle);<br>  draw_shape(triangle);<br><br>  return 0;<br>}</pre><p>The draw_shape function takes a reference to const Drawable&amp;. This allows it to accept objects of any class that implements the Drawable interface (e.g., Circle or Triangle). Inside the function, shape.draw() calls the specific implementation of draw() from the actual object passed (polymorphism).</p><p>In that given example, for just two shapes (Circle and Triangle), inheritance might seem sufficient. But as your project grows and you introduce more unrelated classes that need drawing functionalities, interfaces become a more robust and flexible approach.</p><h3>Key Features of Interfaces</h3><ul><li><strong>Pure Virtual Functions</strong>: Interfaces contain only pure virtual functions, which are declared by using = 0 syntax.</li><li><strong>No Implementation</strong>: Interfaces do not provide any implementation for their methods. However, classes that implement an interface must provide concrete implementations for the specified methods. They promote loose coupling and better code organization by separating the “what” (interface) from the “how” (implementation in classes).</li><li><strong>Multiple Inheritance</strong>: C++ supports multiple inheritance, allowing a class to implement multiple interfaces. Interfaces champion polymorphism, enabling objects of different classes to be treated uniformly through a common interface.</li></ul><blockquote>In essence, interfaces provide a contract that specifies what functionalities a class must provide, while classes provide a complete implementation of those functionalities. This can lead to more flexible, reusable, and maintainable code.</blockquote><h3>SEVEN Major Differences</h3><h4><strong>1| Instantiation:</strong></h4><ul><li><strong>Class:</strong> You can create objects (instances) from a class. These objects hold data (attributes) and define behavior (methods).</li><li><strong>Interface:</strong> An interface itself cannot be used to create objects. It acts as a blueprint that specifies what functionalities a class <strong>must</strong> implement.</li></ul><h4><strong>2| Implementation:</strong></h4><ul><li><strong>Class:</strong> A class can contain a mix of member types: methods (functions that define behavior), attributes (variables that hold data), and constructors (special methods for object initialization). These members can have different access levels (public, private, protected).</li><li><strong>Interface:</strong> An interface only defines methods. These methods have no body (implementation details) and are implicitly declared as public.</li></ul><h4><strong>3| Inheritance:</strong></h4><ul><li><strong>Class:</strong> A class can inherit from only one other class (single inheritance) but can implement multiple interfaces (multiple inheritance).</li><li><strong>Interface:</strong> An interface can inherit from other interfaces, allowing for a hierarchy of functionalities.</li></ul><h4><strong>4| Abstract vs. Concrete:</strong></h4><ul><li><strong>Class:</strong> A class can be abstract, meaning it can have abstract methods (methods with no body) that must be implemented by subclasses. A concrete class provides complete implementations for all its methods.</li><li><strong>Interface:</strong> An interface is inherently abstract. All its methods are implicitly abstract, requiring implementing classes to provide the functionality.</li></ul><h4><strong>5| Members:</strong></h4><ul><li><strong>Class:</strong> A class can have a mix of public, private, and protected members, allowing control over data access and method visibility.</li><li><strong>Interface:</strong> Interfaces can only have public members. This ensures that any class implementing the interface can access its functionalities.</li></ul><h4><strong>6| Focus:</strong></h4><ul><li><strong>Class:</strong> A class is a blueprint for creating objects that encapsulate data and behavior. It defines the “what” (data) and “how” (methods) of an object.</li><li><strong>Interface:</strong> An interface focuses on the “what” aspect. It defines the functionalities (methods) that a class must provide, promoting loose coupling and promoting polymorphism.</li></ul><h4><strong>7| Purpose:</strong></h4><ul><li><strong>Class:</strong> A class is the workhorse of OOP. It serves as the foundation for creating objects that represent real-world entities or concepts.</li><li><strong>Interface:</strong> An interface acts as a contract between a class and the outside world. It specifies the functionalities that a class guarantees to implement, promoting code flexibility and reusability.</li></ul><p>By mastering the art of classes and interfaces, you’ll be well-equipped to construct robust, adaptable, and maintainable C++ applications. Classes provide the blueprint for objects, while interfaces act as contracts, ensuring that diverse objects can interact seamlessly through a common language. As you embark on your C++ journey, remember this dynamic duo — classes and interfaces — as they’ll be your trusted companions in crafting well-structured and efficient object-oriented programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a237a06c0cad" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/unveiling-the-powerhouse-duo-classes-vs-interfaces-in-c-oop-a237a06c0cad">Unveiling the Powerhouse Duo: Classes vs. Interfaces in C++ OOP</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance with access-specifier in cpp]]></title>
            <link>https://towardsdev.com/inheritance-with-specifier-in-cpp-fcd4f29b08e1?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd4f29b08e1</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 05:10:22 GMT</pubDate>
            <atom:updated>2024-06-25T17:45:52.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TlcV_sBjyD64k41p" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When inheriting from a base class, the choice of <strong><em>access specifier</em></strong> determines how the members of the base class will be inherited and what their access level will be in the derived class. The syntax for inheritance is as follows:</p><pre>class ChildClass : [access-specifier] ParentClass {<br>    // ...code...<br>};</pre><p>Let&#39;s dive into the lines of codes:</p><pre>class Parent<br>{<br>private:<br>    int pvt = 12;<br>    <br>protected:<br>    int prot = 42; // A protected member of the Base class<br><br>public:<br>    int pub = 16;<br>};<br><br>class Child1 : public Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};<br><br>class Child2 : protected Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};<br><br>class Child3 : private Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};</pre><p>As you can see we have made three different children of the same parent class namely <strong><em>Parent. </em></strong>Now, the question is :</p><h4>What are the differences between these classes though they contain the exactly same lines of code inside them?</h4><p>In the provided code, there are three classes: Child1, Child2, and Child3, each inheriting from the Parent class with different access specifiers. The access specifiers (public, protected, and private) determine the visibility of the base class members in the derived class. Let&#39;s explore the differences between these classes:</p><h3>Child1: Public Inheritance</h3><pre>class Child1 : public Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};</pre><p>In this case, Child1 publicly inherits from Parent. The protected member prot of the Parent class is accessible in Child1 through its public member function getProt(). Objects of Child1 can access the protected member directly.</p><p><strong>Usage example:</strong></p><pre>Child1 child1Obj;<br>int value = child1Obj.getProt(); // This is valid because getProt() is a public member function.</pre><h3>Child2: Protected Inheritance</h3><pre>class Child2 : protected Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};</pre><p>In this case, Child2 inherits from Parent with a protected specifier. This means that the protected and public members of the Parent class become protected members in Child2. Outside the Child2 class, the protected members are not accessible.</p><p><strong>Usage example:</strong></p><pre>Child2 child2Obj;<br>int value = child2Obj.getProt(); // This is valid because getProt() is a public member function.<br><br>// Accessing prot directly outside the class is not allowed.<br>// int protValue = child2Obj.prot; // This would result in a compilation error.</pre><h3>Child3: Private Inheritance</h3><pre>class Child3 : private Parent<br>{<br>public:<br>    int getProt()<br>    {<br>        return prot;<br>    }<br>};</pre><p>In this case, Child3 inherits from Parent with a private specifier. This means that both the protected and public members of the Parent class become private members in Child3. Outside the Child3 class, the inherited members are not accessible.</p><p><strong>Usage example:</strong></p><pre>Child3 child3Obj;<br>int value = child3Obj.getProt(); // This is valid because getProt() is a public member function.<br><br>// Accessing prot directly outside the class is not allowed.<br>// int protValue = child3Obj.prot; // This would result in a compilation error.</pre><p>To summarize, the main difference lies in the accessibility of the inherited members outside the derived classes. Public inheritance allows access to the inherited members, protected inheritance restricts access to the outside world, and private inheritance makes all inherited members private to the derived class.</p><p>Let’s stay connected on <a href="http://www.linkedin.com/in/khan1203">Linkedin</a> ^_^</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd4f29b08e1" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/inheritance-with-specifier-in-cpp-fcd4f29b08e1">Inheritance with access-specifier in cpp</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Productivity: Five Time-Tested Principles for Success]]></title>
            <link>https://medium.com/@khan1203/mastering-productivity-five-time-tested-principles-for-success-1760455cc681?source=rss-5e1fd8fe5366------2</link>
            <guid isPermaLink="false">https://medium.com/p/1760455cc681</guid>
            <dc:creator><![CDATA[Khan Muhammad Rifat]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 14:19:14 GMT</pubDate>
            <atom:updated>2023-11-23T14:24:47.619Z</atom:updated>
            <content:encoded><![CDATA[<p>In a world that often demands more than we can seemingly accomplish, mastering productivity becomes a crucial skill. Whether you’re a student, a professional, or someone striving for personal growth, the ability to manage your time and tasks efficiently can significantly impact your success. In this blog, we’ll explore five time-tested principles that can help you boost your productivity and achieve your goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q1Z7etus-ygJkaOW" /><figcaption>Photo by <a href="https://unsplash.com/@alterego_swiss?utm_source=medium&amp;utm_medium=referral">AbsolutVision</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>1# Prioritize and Plan: The Foundation of Productivity</strong></h4><p>In the journey of productivity, prioritization is the compass that guides us. By distinguishing the urgent from the important, we pave the way for success. As Dwight D. Eisenhower once said,</p><blockquote>“What is important is seldom urgent, and what is urgent is seldom important ”</blockquote><p>Utilize tools like to-do lists and calendars to plan your workload meticulously. Remember, breaking down larger tasks into smaller, actionable steps is like creating a detailed treasure map of your goals. In the words of Antoine de Saint-Exupéry,</p><blockquote>“A goal without a plan is just a wish.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BwP400yPU_ePFJfV" /><figcaption>Photo by <a href="https://unsplash.com/@jan_huber?utm_source=medium&amp;utm_medium=referral">Jan Huber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>2# Time Blocking: The Power of Immersive Focus</strong></h4><p>Time blocking is the secret sauce that transforms ordinary tasks into extraordinary accomplishments. As Cal Newport wisely advises,</p><blockquote>“Efforts to deepen your focus will struggle if you don’t simultaneously wean your mind from a dependence on distraction”</blockquote><p>Allocate dedicated blocks of time to tasks, creating an environment that minimizes distractions. Flexibility is key; adjust your time blocks to harness your natural energy peaks. Remember, it’s not about managing time, but about managing your attention. In the words of Tony Robbins,</p><blockquote>‘The only limit to your impact is your imagination and commitment.’</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VjcZFxWZIjklnUWw" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>3# SMART Goals: A Blueprint for Achievable Triumphs</h4><p>SMART goals are the architects of achievement, turning dreams into tangible realities. In the wise words of Peter Drucker, ‘What gets measured gets improved.’ Embrace goals that are Specific, Measurable, Achievable, Relevant, and Time-bound. As Brian Tracy encourages,</p><blockquote>‘Your ability to set goals is the master skill of success.’</blockquote><p>Break down your objectives into manageable milestones and regularly review and recalibrate. In the journey to success, goals provide the roadmap, and as Zig Ziglar said, ‘A goal properly set is halfway reached.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OsLxlJ5Yk9rzwWTK" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>4# Two-Minute Rule: Overcoming Procrastination with Precision</h4><p>The two-minute rule is the unsung hero in the battle against procrastination. In the words of David Allen,</p><blockquote>‘If it takes less than two minutes, then do it now.’</blockquote><p>Tackling small tasks immediately prevents them from accumulating and transforming into productivity roadblocks. As Karen Lamb wisely notes, ‘A year from now you may wish you had started today.’ Embrace the two-minute rule as a beacon of productivity, fostering a proactive mindset. In the words of Pablo Picasso, ‘Action is the foundational key to all success.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o47wvpRJPsDTtKzl" /><figcaption>Photo by <a href="https://unsplash.com/@epicantus?utm_source=medium&amp;utm_medium=referral">Daria Nepriakhina 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>5# Breaks and Rest: Nurturing the Productive Mind and Body</h4><p>Rest is the silent partner of productivity, essential for nurturing both the mind and body. As Jim Loehr wisely states,</p><blockquote>‘Performance, health, and happiness are grounded in the skillful management of energy.’</blockquote><p>Regular breaks are not a luxury but a strategic investment in sustained focus. Embrace techniques like the Pomodoro Technique, recognizing that productivity flourishes in the ebb and flow of focused work and intentional rest. As Arianna Huffington advocates,</p><blockquote>‘We think, mistakenly, that success is the result of the amount of time we put in at work, instead of the quality of time we put in.’</blockquote><p>Find me on Linkedin: <a href="https://www.linkedin.com/in/khan1203/">Khan Muhammad Rifat</a><br>Feel free to respond ‘Hi’ or get connected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1760455cc681" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>