<?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 Osini Navoda on Medium]]></title>
        <description><![CDATA[Stories by Osini Navoda on Medium]]></description>
        <link>https://medium.com/@navodaoshini?source=rss-1b28c8b6d2e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WiB0_l-1LgSUcSW4</url>
            <title>Stories by Osini Navoda on Medium</title>
            <link>https://medium.com/@navodaoshini?source=rss-1b28c8b6d2e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:00:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navodaoshini/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[DQL in SQL]]></title>
            <link>https://medium.com/@navodaoshini/dql-in-sql-95e6ceeeff99?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/95e6ceeeff99</guid>
            <category><![CDATA[data-query-language]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 11:31:50 GMT</pubDate>
            <atom:updated>2026-06-06T11:31:50.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQq8e1eNUt9dZV9KSQo-lg.png" /><figcaption>dql</figcaption></figure><p>Most people learn SQL by jumping straight into writing queries without ever stopping to ask — <em>where does SELECT actually fit in the bigger picture?</em> That question matters more than it seems. Understanding the structure of SQL helps you write better queries, debug faster, and explain your work clearly to others.</p><p>This article focuses entirely on <strong>DQL — Data Query Language</strong> — the part of SQL dedicated to one thing: retrieving data. By the end, you will have a solid understanding of 15 different queries, what they do, why they exist, and when to use them.</p><h3>What Is DQL?</h3><p>SQL is not a single language — it is a collection of sub-languages, each designed for a different purpose:</p><ul><li><strong>DDL (Data Definition Language)</strong> — creates and modifies database structure (CREATE, ALTER, DROP)</li><li><strong>DML (Data Manipulation Language)</strong> — inserts, updates, and deletes data (INSERT, UPDATE, DELETE)</li><li><strong>DCL (Data Control Language)</strong> — manages permissions (GRANT, REVOKE)</li><li><strong>TCL (Transaction Control Language)</strong> — controls transactions (COMMIT, ROLLBACK)</li><li><strong>DQL (Data Query Language)</strong> — retrieves data (SELECT)</li></ul><p>DQL is focused entirely on <em>reading</em> data. It does not modify anything in the database. It does not add rows, remove rows, or change the schema. It simply asks a question and returns an answer.</p><p>The core — and technically only — command in DQL is SELECT. But do not let that simplicity fool you. The SELECT statement is one of the most powerful tools in SQL when you understand all the clauses that work alongside it.</p><h3>The Table We Will Use</h3><p>All examples in this article use a single table called employees. Here is how it is structured:</p><pre>CREATE TABLE employees (<br>  id          INT PRIMARY KEY,<br>  name        VARCHAR(50),<br>  department  VARCHAR(50),<br>  salary      DECIMAL(10, 2),<br>  city        VARCHAR(50),<br>  join_date   DATE<br>);</pre><p>Think of it as a company database with records for each employee — their name, which department they belong to, their salary, the city they work from, and the date they joined.</p><h3>Query 1 — SELECT All Columns</h3><pre>SELECT * FROM employees;</pre><p>This is the most basic query you can write. The asterisk * is a wildcard that tells SQL to return every column in the table. Every row is returned as well since there is no filter applied.</p><p>This is useful when you are first exploring a table and want to see what data it holds. In real production work, though, it is considered bad practice to use SELECT * because it pulls unnecessary data, slows down performance, and makes your code harder to maintain. Name your columns explicitly whenever possible.</p><h3>Query 2 — SELECT Specific Columns</h3><pre>SELECT name, department, salary<br>FROM employees;</pre><p>Here we are telling the database exactly which columns we want. Only name, department, and salary will appear in the result — nothing else.</p><p>This is always the preferred approach. It makes your query readable, reduces the data being transferred, and gives the reader of your code an immediate understanding of what the query is about.</p><h3>Query 3 — WHERE Clause</h3><pre>SELECT name, city<br>FROM employees<br>WHERE city = &#39;Colombo&#39;;</pre><p>The WHERE clause filters rows based on a condition. Only rows where the city column equals ‘Colombo’ will be included in the result. Every other row is excluded before the data is returned.</p><p>WHERE supports a wide range of operators — =, !=, &gt;, &lt;, &gt;=, &lt;= — and works with text, numbers, and dates equally well. It is the most fundamental filtering tool in SQL and appears in almost every real-world query.</p><h3>Query 4 — AND / OR Conditions</h3><pre>// Must satisfy both conditions<br>SELECT name, salary<br>FROM employees<br>WHERE department = &#39;Engineering&#39; AND salary &gt; 60000;</pre><p>— Must satisfy at least one condition SELECT name, city FROM employees WHERE city = ‘Colombo’ OR city = ‘Kandy’;</p><p>You can chain multiple conditions in a WHERE clause using AND and OR.</p><p>AND requires both conditions to be true for a row to be included. OR includes a row if either condition is true. You can combine them in complex filters, but be careful about operator precedence — use parentheses when mixing both in the same query to make your intent explicit and avoid logic errors.</p><h3>Query 5 — ORDER BY</h3><pre>-- Highest salary first<br>SELECT name, salary<br>FROM employees<br>ORDER BY salary DESC;</pre><p>— Alphabetical by name SELECT name FROM employees ORDER BY name ASC;</p><p>ORDER BY sorts the result set. ASC (ascending) is the default — it goes from the smallest value to the largest, or A to Z for text. DESC (descending) reverses that order.</p><p>You can also sort by multiple columns. For example, ORDER BY department ASC, salary DESC would group employees by department alphabetically, then sort by salary from highest to lowest within each department.</p><h3>Query 6 — LIMIT</h3><pre>SELECT name, salary<br>FROM employees<br>ORDER BY salary DESC<br>LIMIT 10;</pre><p>LIMIT restricts how many rows are returned. Combined with ORDER BY, this becomes one of the most practical patterns in SQL — commonly used for “top N” reports.</p><p>The query above returns the 10 highest-paid employees. Without the ORDER BY, LIMIT would just return the first 10 rows it encounters, which may not be meaningful. Always pair LIMIT with an ORDER BY to get predictable, intentional results.</p><p>Note: In SQL Server, the equivalent syntax is SELECT TOP 10 … instead of appending LIMIT.</p><h3>Query 7 — DISTINCT</h3><pre>SELECT DISTINCT department<br>FROM employees;</pre><p>Without DISTINCT, if 50 employees are in the Engineering department, the word “Engineering” would appear 50 times in your results. DISTINCT removes duplicate values and returns each unique entry only once.</p><p>This is particularly useful when you need to understand what unique values exist in a column — for example, finding all the different cities your employees are based in, or all the departments in a company — without repeating information.</p><h3>Query 8 — Aggregate Functions</h3><pre>-- Count total employees<br>SELECT COUNT(*) AS total_employees FROM employees;</pre><p>— Total salary cost SELECT SUM(salary) AS total_salary FROM employees;</p><p>— Average salary SELECT AVG(salary) AS average_salary FROM employees;</p><p>— Highest and lowest salaries SELECT MAX(salary) AS highest_salary, MIN(salary) AS lowest_salary FROM employees;</p><p>Aggregate functions compute a single result from a set of rows. They are the backbone of any reporting or analysis query.</p><ul><li>COUNT() — counts how many rows match</li><li>SUM() — adds up numeric values</li><li>AVG() — calculates the arithmetic mean</li><li>MAX() — finds the largest value</li><li>MIN() — finds the smallest value</li></ul><p>The AS keyword creates an alias — a readable label for the result column. Always use aliases with aggregate functions so your output columns have meaningful names instead of AVG(salary) printed as a header.</p><h3>Query 9 — GROUP BY</h3><pre>SELECT department, COUNT(*) AS headcount, AVG(salary) AS avg_salary<br>FROM employees<br>GROUP BY department;</pre><p>GROUP BY divides rows into groups based on a column, then applies aggregate functions to each group separately.</p><p>This query answers: <em>“For each department, how many employees are there and what is their average salary?”</em> Without GROUP BY, COUNT(*) would give you one number for the entire table. With it, you get one row per department.</p><p>A key rule to remember: every column in your SELECT clause must either appear in GROUP BY or be wrapped in an aggregate function. If you try to SELECT name without grouping by it, the database will throw an error because it does not know which name to show for a group of 30 people.</p><h3>Query 10 — HAVING</h3><pre>SELECT department, COUNT(*) AS headcount<br>FROM employees<br>GROUP BY department<br>HAVING COUNT(*) &gt; 5;</pre><p>HAVING filters groups after GROUP BY has already been applied. It works similarly to WHERE, but for aggregated data.</p><p>The reason WHERE cannot be used here is timing — WHERE filters rows <em>before</em> grouping happens, so aggregate values like COUNT(*) do not exist yet at that stage. HAVING runs <em>after</em> grouping, so it can filter based on those computed values.</p><p>The query above returns only departments that have more than 5 employees. Departments with 5 or fewer are excluded from the result.</p><h3>Query 11 — LIKE</h3><pre>-- Names that start with the letter A<br>SELECT name FROM employees WHERE name LIKE &#39;A%&#39;;</pre><p>— Names that contain ‘an’ anywhere SELECT name FROM employees WHERE name LIKE ‘%an%’;</p><p>— Names with exactly 5 characters SELECT name FROM employees WHERE name LIKE ‘_____’;</p><p>LIKE enables pattern-based filtering using two wildcard characters:</p><ul><li>% matches any sequence of characters, including none</li><li>_ matches exactly one character</li></ul><p>This is useful for partial text searches — searching for names starting with a letter, finding records containing a keyword, or matching specific character patterns. Most database search features are built on LIKE under the hood.</p><h3>Query 12 — BETWEEN</h3><pre>-- Employees with salary between 40,000 and 80,000<br>SELECT name, salary<br>FROM employees<br>WHERE salary BETWEEN 40000 AND 80000;</pre><p>— Employees who joined in 2023 SELECT name, join_date FROM employees WHERE join_date BETWEEN ‘2023–01–01’ AND ‘2023–12–31’;</p><p>BETWEEN filters rows where a value falls within a defined range. It works with numbers, dates, and even text.</p><p>An important detail: BETWEEN is inclusive on both ends — a salary of exactly 40,000 or exactly 80,000 would be included in the results above. This is equivalent to writing WHERE salary &gt;= 40000 AND salary &lt;= 80000, but BETWEEN is cleaner and easier to read.</p><h3>Query 13 — IN</h3><pre>SELECT name, city<br>FROM employees<br>WHERE city IN (&#39;Colombo&#39;, &#39;Galle&#39;, &#39;Kandy&#39;);</pre><p>IN lets you match a column against a list of values. This query returns every employee whose city is one of the three listed.</p><p>Without IN, you would need to write WHERE city = ‘Colombo’ OR city = ‘Galle’ OR city = ‘Kandy’. That works, but it becomes unreadable fast as the list grows. IN keeps it clean and is easier to update.</p><p>You can also use NOT IN to exclude a list of values — for example, returning all employees who are <em>not</em> in those three cities.</p><h3>Query 14 — Subquery</h3><pre>-- Employees earning above the company average<br>SELECT name, salary<br>FROM employees<br>WHERE salary &gt; (SELECT AVG(salary) FROM employees);</pre><p>A subquery is a query written inside another query. The inner query runs first and produces a result, which the outer query then uses as part of its own logic.</p><p>In this example, the inner query SELECT AVG(salary) FROM employees computes the average salary across all employees. The outer query then uses that number as a filter — returning only employees who earn more than that average.</p><p>Subqueries can appear in the SELECT, FROM, or WHERE clause. They are one of the most powerful tools in SQL because they allow dynamic filtering without hardcoding values.</p><h3>Query 15 — JOIN</h3><pre>-- Assume a &#39;departments&#39; table with dept_id and dept_name<br>SELECT e.name, e.salary, d.dept_name<br>FROM employees e<br>INNER JOIN departments d ON e.department = d.dept_id;</pre><p>In real databases, data is spread across multiple tables. JOIN connects them using a common column — in this case, the department identifier.</p><p>INNER JOIN returns only the rows where a match exists in both tables. If an employee has a department ID that does not exist in the departments table, that row is excluded.</p><p>Other join types include:</p><ul><li>LEFT JOIN — returns all rows from the left table, and matched rows from the right. Unmatched rows on the right appear as NULL.</li><li>RIGHT JOIN — the reverse of LEFT JOIN.</li><li>FULL OUTER JOIN — returns all rows from both tables, with NULLs where there is no match.</li></ul><p>JOINs are what make relational databases relational. Mastering them is essential for working with any real-world dataset.</p><h3>Putting It All Together</h3><p>The real power of DQL shows when you combine these clauses in a single query:</p><pre>SELECT d.dept_name, COUNT(*) AS headcount, ROUND(AVG(e.salary), 2) AS avg_salary<br>FROM employees e<br>INNER JOIN departments d ON e.department = d.dept_id<br>WHERE e.join_date &gt;= &#39;2022-01-01&#39;<br>GROUP BY d.dept_name<br>HAVING COUNT(*) &gt;= 3<br>ORDER BY avg_salary DESC<br>LIMIT 5;</pre><p>This one query:</p><ul><li>Joins two tables</li><li>Filters employees who joined from 2022 onwards</li><li>Groups by department name</li><li>Calculates headcount and average salary per department</li><li>Excludes departments with fewer than 3 qualifying employees</li><li>Sorts by average salary, highest first</li><li>Returns only the top 5 results</li></ul><p>Understanding each clause individually is step one. Knowing how to layer them together is where SQL fluency actually begins.</p><h3>Clause Execution Order</h3><p>One thing that confuses many beginners is that SQL does not execute in the order you write it. The actual order is:</p><ol><li>FROM — identify the source table</li><li>JOIN — bring in related tables</li><li>WHERE — filter individual rows</li><li>GROUP BY — group filtered rows</li><li>HAVING — filter groups</li><li>SELECT — choose which columns to return</li><li>ORDER BY — sort the result</li><li>LIMIT — restrict the number of rows</li></ol><p>Understanding this order explains why you cannot use a SELECT alias in a WHERE clause (WHERE runs before SELECT), and why HAVING must be used instead of WHERE when filtering aggregate values.</p><h3>Summary</h3><ul><li><strong>SELECT</strong> — choose which columns to retrieve</li><li><strong>WHERE</strong> — filter rows before grouping</li><li><strong>ORDER BY</strong> — sort the result set</li><li><strong>LIMIT</strong> — cap the number of returned rows</li><li><strong>DISTINCT</strong> — eliminate duplicate values</li><li><strong>GROUP BY</strong> — group rows for aggregation</li><li><strong>HAVING</strong> — filter groups after aggregation</li><li><strong>LIKE</strong> — pattern-based text filtering</li><li><strong>BETWEEN</strong> — range-based filtering</li><li><strong>IN</strong> — match against a list of values</li><li><strong>Subquery</strong> — embed one query inside another</li><li><strong>JOIN</strong> — combine data from multiple tables</li><li><strong>Aggregate Functions</strong> — COUNT, SUM, AVG, MAX, MIN</li></ul><p>DQL is the most-used part of SQL in day-to-day work. Whether you are building reports, analyzing trends, or powering a backend API, almost every interaction with a database starts with a SELECT. The more comfortable you get with these building blocks, the more naturally complex queries will come to you.</p><p>Learn one clause at a time. Test each one against real data. And write every query as if someone else has to read it — because eventually, they will.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95e6ceeeff99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolution Of Data Storing]]></title>
            <link>https://medium.com/@navodaoshini/evolution-of-data-storing-7333cabcfb14?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7333cabcfb14</guid>
            <category><![CDATA[dbs]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[evolution-of-data-storing]]></category>
            <category><![CDATA[dbms-and-rdbms]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Thu, 28 May 2026 13:50:33 GMT</pubDate>
            <atom:updated>2026-05-28T13:50:33.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVwFAeBorYoakcrtWvEBdA.png" /><figcaption>Evolution Of Data Storing</figcaption></figure><p>It’s 1955. You work at a bank. Every single customer’s account, their name, their balance, their transaction history, lives inside a folder. Physical paper folders, stacked in metal cabinets, row after row after row.</p><p>Now imagine 10,000 customers. A hundred thousand. A million.</p><p>Someone drops a cabinet. A fire breaks out. Two clerks update the same account at the same time. A new employee misfiled three hundred records last Tuesday and nobody noticed yet.</p><p>This was the world before databases. And the story of how we fixed it? That’s one of the most exciting stories in all of computing.</p><p>Let’s go through it, era by era, like chapters of a thriller.</p><h3>Chapter 1: File-Based Systems — The Wild West of Data (1950s)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*KkdudtxISpiBGJE3.jpg" /></figure><p>The first computers arrived, and people were thrilled. <em>Finally</em>, machines that could store and retrieve information without paper folders!</p><p>But here’s what nobody had figured out yet: <strong>how</strong> to organize that information.</p><p>The answer they came up with was simple: <strong>files</strong>. Just like folders on your desktop today, programs stored their data in flat files, rows of text, one after another. Each application managed its own files in its own format.</p><p>Sounds fine, right? It wasn’t.</p><p>Here’s what happened in practice:</p><p><strong>File Isolation.</strong> The payroll program had its own employee file. The HR program had <em>its own</em> employee file. They never talked to each other. Same data, stored twice, in two different places.</p><p><strong>Application Dependency.</strong> If you changed the structure of a file, every program that used it broke. Updating one thing meant touching everything.</p><p><strong>Data Redundancy and Inconsistency.</strong> John Smith’s salary was updated in the payroll file. Nobody updated the HR file. Now the company has two different numbers for John Smith’s salary. Which one is right? Nobody knows.</p><p><strong>No Concurrent Access.</strong> If two people tried to update the same file at the same time, data got corrupted. The system wasn’t built for teamwork.</p><p><strong>Hard Searching.</strong> Want to find all employees who earn over $50,000 and joined after 2010? You’d have to read <em>every single record</em> in the file, manually. There was no smart searching.</p><p><strong>No Relationships.</strong> Data lived in isolation. There was no way to say “this order belongs to <em>this</em> customer” without duplicating information everywhere.</p><p><strong>Security Issues.</strong> Anyone with access to the file could see everything. There was no concept of “show this person only what they need to see.”</p><p>The world needed something smarter. And in the 1960s, it arrived.</p><h3>Chapter 2: Hierarchical Database — The Family Tree Model (1960s)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*vx5uft5_NO5X2IwH" /></figure><p>IBM looked at the chaos of file systems and asked: <em>“What if data had structure? What if records had parents and children?”</em></p><p>The <strong>Hierarchical Database</strong> was born, and it organized data exactly like a family tree.</p><p>Picture it: at the top, you have a <strong>Company</strong>. Below that, <strong>Departments</strong>. Below each department, <strong>Employees</strong>. Each employee has <strong>Transactions</strong>. Every record had one parent and could have many children. Clean. Logical. Organized.</p><p>IBM’s <strong>IMS (Information Management System)</strong>, launched in 1966 to support the Apollo moon program, was the most famous example. Yes, the database structure that helped put humans on the moon was hierarchical.</p><p><strong>What it solved:</strong></p><ul><li>Data finally had relationships. A record didn’t float in isolation anymore.</li><li>It was fast. If you knew the path to your data, retrieval was blazing quick.</li><li>Large organizations like banks and airlines adopted it enthusiastically.</li></ul><p><strong>But here’s the problem.</strong></p><p>Real life isn’t a perfect tree. What if an employee works in <em>two</em> departments? In a hierarchical database, that’s nearly impossible. A record can only have <em>one</em> parent. You’d have to duplicate the employee in both departments, bringing back the exact redundancy problem file systems had.</p><p>And navigating the tree was painful. To get from one branch to another, you had to climb all the way up to the root and back down. Imagine having to go through the CEO just to move between two departments.</p><p>The tree was tidy, but the world was messier than a tree.</p><h3>Chapter 3: Network Database — The Web of Everything (1970s)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*8Rv3EsxsLzMzGQB_.jpg" /></figure><p>If the hierarchical model was a tree, the <strong>Network Database</strong> was a web.</p><p>In the early 1970s, Charles Bachman introduced a new idea: what if a record could have <em>multiple</em> parents? What if data could link to other data in any direction?</p><p>Now an employee <em>could</em> belong to two departments. A product <em>could</em> be listed in multiple orders. A student <em>could</em> enroll in multiple courses. The web of connections finally matched the complexity of the real world.</p><p>This was a genuinely exciting leap. Network databases powered some of the most critical systems of the era, airline reservation systems, banking networks, manufacturing logistics.</p><p><strong>But there was a catch, a big one.</strong></p><p>To use a network database, developers had to write <em>navigation code</em>. They had to tell the computer <em>exactly how to walk</em> through the web of links to find their data. Step by step. Node by node.</p><p>If the database structure changed, say, you added a new type of connection, you had to rewrite all your navigation code. Every program that touched the database became fragile, tightly coupled to the exact shape of the data.</p><p>It was powerful but exhausting to maintain.</p><p>Somewhere, a quiet mathematician was thinking: <em>“There has to be a better way.”</em></p><h3>Chapter 4: The Relational Database — The Revolution That Changed Everything (1970s-1980s)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*9RvvfW-gLAJYfKYj.jpg" /></figure><p><em>This is the chapter where everything changes.</em></p><p>In 1970, an IBM researcher named <strong>Edgar F. Codd</strong> published a paper that would reshape computing forever.</p><p>His idea was almost embarrassingly simple: <strong>store data in tables</strong>.</p><p>Not trees. Not webs. Just flat, two-dimensional tables, rows and columns, like a spreadsheet. And crucially, let the <em>database</em> figure out how to connect the tables. The programmer shouldn’t have to navigate anything manually.</p><p>He called it the <strong>Relational Model</strong>.</p><p>Here’s the magic of it. Imagine two tables:</p><p><strong>Customers Table:</strong></p><p>CustomerID Name City 1 Alice London 2 Bob New York</p><p><strong>Orders Table:</strong></p><p>OrderID CustomerID Product 101 1 Laptop 102 2 Phone</p><p>Want to know what Alice ordered? Just ask: <em>“Give me all orders where CustomerID = 1.”</em> Done. No navigation. No tree climbing. Just a simple question in plain logical language.</p><p>That language became <strong>SQL</strong>, Structured Query Language. And it turned database querying from a programmer’s nightmare into something almost readable as plain English.</p><p>Larry Ellison read Codd’s paper, saw the future, and in 1977 co-founded a company to build the first commercial relational database. That company? <strong>Oracle</strong>.</p><p>IBM followed. Microsoft followed. The entire software industry followed.</p><p>Relational databases became the backbone of the modern world. Every e-commerce order, every bank transaction, every hospital record, most of it still runs on relational databases today.</p><h3>Chapter 5: NoSQL — When Rules Need to Break (2000s to Present)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*QeXJjOOynfN364hh" /></figure><p>For thirty years, relational databases ruled without question.</p><p>Then the internet happened. And suddenly, everything changed.</p><p>In the 2000s, companies like Google, Facebook, and Amazon were building applications that had never existed before. Millions of simultaneous users. Petabytes of data. Content that didn’t fit neatly into rows and columns, social media posts, product catalogs, user preferences, real-time clickstreams.</p><p>Relational databases began to groan under the weight.</p><p>The problem? Rigid schemas. To store data in a relational database, you had to define the <em>exact structure</em> of your data upfront, every column, every data type, every relationship. In a world where your product catalog changes daily and your users generate unpredictable data, that rigidity became a bottleneck.</p><p><strong>NoSQL</strong> (which stands for “Not Only SQL”) exploded onto the scene as the answer.</p><p>Instead of forcing everything into tables, NoSQL databases offered flexible alternatives:</p><p><strong>Document Databases</strong> <em>(like MongoDB)</em> store data as JSON-like documents. Each record can have its own unique structure. No rigid schema required. Perfect for content-heavy applications.</p><p><strong>Key-Value Stores</strong> <em>(like Redis)</em> follow the simplest model: every piece of data has a unique key. Lightning-fast lookups. Ideal for caching, sessions, and real-time leaderboards.</p><p><strong>Column-Family Stores</strong> <em>(like Apache Cassandra)</em> are designed for massive write-heavy workloads. Used by Netflix, Instagram, and Discord to handle billions of writes per day.</p><p><strong>Graph Databases</strong> <em>(like Neo4j)</em> store data as nodes and relationships. Perfect for social networks, fraud detection, and recommendation engines.</p><p><strong>What makes NoSQL special:</strong></p><p><strong>Flexible Schemas.</strong> Add new fields to individual records on the fly, without touching the rest of the database.</p><p><strong>Horizontal Scalability.</strong> Instead of buying one huge powerful server, spread your data across hundreds of smaller ones. Scale out, not up.</p><p><strong>High Performance.</strong> Optimized for the rapid, large-scale read and write operations that modern applications demand.</p><p><strong>When should you use NoSQL?</strong> When your data is rapidly changing. When you’re handling massive volumes of unstructured content. When you need to scale instantly without downtime. When your application’s data model doesn’t fit neatly into tables.</p><p>Facebook’s social graph. Airbnb’s listing catalog. Amazon’s shopping cart. These run on NoSQL, because some problems are genuinely too messy for a tidy table.</p><h3>Chapter 6: Cloud Databases — Your Database, Anywhere (2010s to Present)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*EQlv5Pj4gSsGoy4m.png" /></figure><p>The final chapter of our story is still being written.</p><p>For most of computing history, if you needed a database, you needed a <em>server</em>. A physical machine, sitting somewhere in your building, maintained by your IT team, consuming power 24 hours a day.</p><p>Then Amazon, Google, and Microsoft asked a different question: <em>“What if the server was our problem, not yours?”</em></p><p><strong>Cloud databases</strong> are database services built, deployed, and accessed entirely over the internet. You don’t buy hardware. You don’t install software. You don’t worry about backups or security patches or what happens when a hard drive fails.</p><p>You just connect and use.</p><p><strong>The big three of cloud databases:</strong></p><p><strong>Amazon Web Services (AWS)</strong></p><ul><li><em>Amazon RDS</em> is a managed relational database supporting MySQL, PostgreSQL, and more.</li><li><em>DynamoDB</em> is AWS’s flagship NoSQL database, built for massive scale.</li></ul><p><strong>Google Cloud</strong></p><ul><li><em>Cloud SQL</em> handles managed MySQL and PostgreSQL.</li><li><em>Cloud Spanner</em> is a relational database that scales globally across multiple continents simultaneously, something that was considered theoretically impossible until Google built it.</li></ul><p><strong>Microsoft Azure</strong></p><ul><li><em>Azure SQL Database</em> is a fully managed SQL Server in the cloud.</li><li><em>Cosmos DB</em> is a globally distributed multi-model database.</li></ul><p><strong>What cloud changes:</strong></p><ul><li>A startup in Colombo can now run the same database infrastructure as a Fortune 500 company.</li><li>Databases automatically scale when traffic spikes, so your website doesn’t crash on launch day.</li><li>Automatic backups, automatic failover, automatic security updates.</li><li>Pay only for what you use. No hardware. No upfront investment.</li></ul><p>The cloud didn’t just make databases cheaper. It democratized access to world-class infrastructure for anyone with a credit card and an idea.</p><h3>The Full Journey at a Glance</h3><p>Era Model Key Problem Solved Key Limitation 1950s File Systems Basic digital storage Isolated, redundant, fragile 1960s Hierarchical DB Data relationships Only one parent per record 1970s Network DB Multiple relationships Complex navigation code 1970–80s Relational DB Simple queries, SQL Rigid schemas, hard to scale 2000s NoSQL Flexible, scalable No universal query standard 2010s+ Cloud DB Accessible, managed Vendor lock-in, internet dependency</p><h3>Why This Story Matters to You</h3><p>You don’t have to be a database engineer to care about this evolution.</p><p>Every app on your phone is powered by one of these systems. Every time you check your bank account, search for a product, or get a Netflix recommendation, a database somewhere made that possible.</p><p>And we’re still evolving. <strong>NewSQL</strong> databases are trying to combine the scalability of NoSQL with the reliability of relational systems. <strong>AI-native databases</strong> are being designed to store and query vector data for machine learning models. <strong>Serverless databases</strong> are making the infrastructure entirely invisible.</p><p>The story that started with a paper folder in 1955?</p><p>It’s nowhere near finished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7333cabcfb14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linked Lists & Stacks: When Arrays Just Aren’t Enough]]></title>
            <link>https://medium.com/@navodaoshini/linked-lists-stacks-when-arrays-just-arent-enough-d5a02cdf9213?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a02cdf9213</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 07:30:16 GMT</pubDate>
            <atom:updated>2026-04-26T07:30:16.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEKNcbTIQqIuZtAhO2Lm1A.png" /></figure><h4>DSA Series — Part 2</h4><p>If you read Part 1 of this series, you already know how arrays work. They’re fast, simple, and great for a lot of things. But here’s the honest truth — <strong>arrays have a weakness</strong>. And once you see it, you can’t unsee it.</p><p>Imagine you have a playlist of 1,000 songs and you want to insert a new song at position 2. With an array, you have to <em>shift every single song after that point</em> to make room. That’s 998 moves for one insert. Not ideal.</p><p>This is exactly why <strong>Linked Lists</strong> exist. And once we understand them, we’ll naturally arrive at one of the most powerful tools in programming — the <strong>Stack</strong>.</p><p>Let’s break it all down, simply.</p><h3>Part 1: The Problem With Arrays (And How Linked Lists Fix It)</h3><p>Think of an array like seats in a movie theater — each seat has a fixed number, and everyone sits next to each other in a row. If someone new wants to sit in seat 3, everyone from seat 3 onwards has to scoot down. Painful.</p><p>A <strong>linked list</strong> is more like a treasure hunt. Each clue (node) tells you where the next clue is. The items don’t need to sit next to each other in memory — they just need to know where the next one is.</p><p>here are some opration and lets figher out whats better</p><p>access by index — array O(1) — instant ..Linked List O(n) — must walk</p><p>Insert at beginning — Linked List O(1) — just redirect</p><p>Delete from middle —Linked List O(1)* — just redirect</p><p>Search -both are o(n)</p><p>Append to end — array O(1) amortized</p><p><strong>Simple rule of thumb:</strong></p><ul><li>Use <strong>arrays</strong> when you need to access items by position frequently.</li><li>Use <strong>linked lists</strong> when you’re inserting or deleting a lot, especially in the middle.</li></ul><p>Real-world examples where linked lists shine: music playlists, browser history, undo systems.</p><h3>Part 2: Building a Linked List From Scratch</h3><h3>The Node — The LEGO Brick of Linked Lists</h3><p>Every linked list is made up of <strong>nodes</strong>. A node is simple — it holds two things:</p><ol><li>The <strong>data</strong> you want to store</li><li>A <strong>pointer</strong> to the next node</li></ol><pre>class Node:<br>    def __init__(self, data):<br>        self.data = data<br>        self.next = None  # Points to the next node (or nothing)</pre><p>Visually, three connected nodes look like this:</p><pre>[10 | →] ——&gt; [20 | →] ——&gt; [30 | None]<br> head</pre><p>The list only keeps track of the first node (the <strong>head</strong>). To get to any other node, you follow the chain of pointers.</p><h3>The LinkedList Class</h3><pre>class LinkedList:<br>    def __init__(self):<br>        self.head = None  # Empty list to start</pre><p>That’s it. Just one pointer to the first node.</p><h3>Core Operations</h3><p><strong>Append — Add to the End</strong></p><p>Walk to the last node, then attach the new node to it.</p><pre>def append(self, data):<br>    new_node = Node(data)<br>    if not self.head:           # List is empty<br>        self.head = new_node<br>        return<br>    current = self.head<br>    while current.next:         # Walk to the last node<br>        current = current.next<br>    current.next = new_node     # Attach</pre><p><strong>Prepend — Add to the Front (O(1) )</strong></p><p>No walking needed. Just point the new node at the old head, and make it the new head.</p><pre>def prepend(self, data):<br>    new_node = Node(data)<br>    new_node.next = self.head   # New node points to old head<br>    self.head = new_node        # New node is now the head</pre><p>This is why linked lists are so powerful for front-insertions — it’s just two pointer updates.</p><p><strong>Delete a Node</strong></p><p>The key idea: to remove a node, you make the node <em>before it</em> skip over it.</p><pre>def delete(self, data):<br>    if not self.head:<br>        return<br>    if self.head.data == data:      # Special case: deleting the head<br>        self.head = self.head.next<br>        return<br>    current = self.head<br>    while current.next:<br>        if current.next.data == data:<br>            current.next = current.next.next  # Skip over the target node<br>            return<br>        current = current.next</pre><blockquote><em>Deleting the head is always a special case. There’s no node “before” the head, so you handle it separately.</em></blockquote><h3>Part 3: Classic Problems</h3><h3>Reverse a Linked List</h3><p>This is <em>the</em> most common linked list interview question. The idea is to flip all the arrows.</p><pre>Before: head → [1] → [2] → [3] → None<br>After:  head → [3] → [2] → [1] → None</pre><p>You do this with three pointers doing a careful dance:</p><pre>def reverse(self):<br>    prev = None<br>    current = self.head<br>    while current:<br>        next_node = current.next    # 1. Save where we&#39;re going<br>        current.next = prev         # 2. Flip the arrow<br>        prev = current              # 3. Move prev forward<br>        current = next_node         # 4. Move current forward<br>    self.head = prev</pre><p>The most critical line: <strong>save </strong><strong>next_node BEFORE flipping the pointer.</strong> If you flip first, you lose the rest of the list forever.</p><h3>Find the Middle Node &amp; Detect Cycles — The Slow/Fast Pointer Trick</h3><p>Here’s an elegant trick: use <strong>two pointers</strong> — one slow (moves 1 step) and one fast (moves 2 steps).</p><p><strong>Find the Middle:</strong></p><p>When the fast pointer reaches the end, the slow pointer is exactly at the middle.</p><pre>def find_middle(self):<br>    slow = self.head<br>    fast = self.head<br>    while fast and fast.next:<br>        slow = slow.next        # 1 step<br>        fast = fast.next.next   # 2 steps<br>    return slow.data</pre><p><strong>Detect a Cycle (Floyd’s Algorithm — “Tortoise and Hare”):</strong></p><p>If a cycle exists, the fast pointer will eventually lap the slow pointer and they’ll meet. If there’s no cycle, fast reaches None and exits.</p><pre>def has_cycle(self):<br>    slow = self.head<br>    fast = self.head<br>    while fast and fast.next:<br>        slow = slow.next<br>        fast = fast.next.next<br>        if slow == fast:        # They met — cycle detected!<br>            return True<br>    return False                # Fast reached end — no cycle</pre><p>This single pattern (slow + fast pointers) solves multiple problems. Memorize it.</p><h3>Part 4: Doubly Linked Lists — A Quick Look</h3><p>A <strong>doubly linked list</strong> gives each node an extra pointer — one pointing forward, one pointing backward.</p><pre>None ←← [A] ↔ [B] ↔ [C] →→ None</pre><p>This lets you traverse in <em>both directions</em> — perfect for browser back/forward navigation. The trade-off is a little extra memory per node (one extra pointer).</p><p>Use singly linked when: one direction is enough. Use doubly linked when: you need to go backwards, or want O(1) deletion with just a node reference.</p><h3>Part 5: Stacks — Simple, But Incredibly Powerful</h3><h3>What’s a Stack?</h3><p>A <strong>stack</strong> follows one simple rule: <strong>Last In, First Out (LIFO).</strong></p><p>Think of a stack of plates. You add plates to the top, and you take from the top. You can’t grab the plate at the bottom without moving everything above it.</p><p>The two main operations:</p><ul><li><strong>push</strong> — put something on top</li><li><strong>pop</strong> — take something off the top</li></ul><h3>Building a Stack in Python</h3><p>Python lists already behave like stacks. We just wrap them:</p><pre>class Stack:<br>    def __init__(self):<br>        self.items = []</pre><pre>    def push(self, item):<br>        self.items.append(item)       # Add to top</pre><pre>    def pop(self):<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self.items.pop()       # Remove from top</pre><pre>    def peek(self):<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self.items[-1]         # Look at top without removing</pre><pre>    def is_empty(self):<br>        return len(self.items) == 0</pre><pre>    def size(self):<br>        return len(self.items)</pre><p><strong>Every single operation is O(1).</strong> That’s what makes stacks so fast and useful.</p><h3>Part 6: Stack in Action — Real Problems</h3><h3>Balanced Parentheses</h3><p>This is <em>the</em> canonical stack problem. Given a string like &quot;({[]})&quot;, determine if every opening bracket has a matching closing bracket in the right order.</p><p><strong>The idea:</strong></p><ul><li>When you see an opening bracket ( [ { → push it onto the stack</li><li>When you see a closing bracket ) ] } → pop from the stack and check if it matches</li><li>At the end, if the stack is empty → balanced</li></ul><pre>def is_balanced(expression):<br>    stack = Stack()<br>    matching = {&#39;)&#39;: &#39;(&#39;, &#39;]&#39;: &#39;[&#39;, &#39;}&#39;: &#39;{&#39;}</pre><pre>    for char in expression:<br>        if char in &#39;([{&#39;:<br>            stack.push(char)<br>        elif char in &#39;)]}&#39;:<br>            if stack.is_empty():<br>                return False              # Nothing to match with<br>            if stack.pop() != matching[char]:<br>                return False              # Wrong match<br>    <br>    return stack.is_empty()               # Leftover = unmatched brackets</pre><p>Let’s trace through &quot;({[]})&quot;:</p><pre>&#39;(&#39; → push  |  Stack: [&#39;(&#39;]<br>&#39;{&#39; → push  |  Stack: [&#39;(&#39;, &#39;{&#39;]<br>&#39;[&#39; → push  |  Stack: [&#39;(&#39;, &#39;{&#39;, &#39;[&#39;]<br>&#39;]&#39; → pop &#39;[&#39; → matches? ✅  |  Stack: [&#39;(&#39;, &#39;{&#39;]<br>&#39;}&#39; → pop &#39;{&#39; → matches? ✅  |  Stack: [&#39;(&#39;]<br>&#39;)&#39; → pop &#39;(&#39; → matches? ✅  |  Stack: []<br>Stack is empty → BALANCED ✅</pre><h3>Reverse a String</h3><p>Stacks make string reversal trivial — push all characters, then pop them. LIFO takes care of the rest.</p><pre>def reverse_string(s):<br>    stack = Stack()<br>    for char in s:<br>        stack.push(char)<br>    <br>    result = &quot;&quot;<br>    while not stack.is_empty():<br>        result += stack.pop()<br>    <br>    return result</pre><pre>print(reverse_string(&quot;hello&quot;))  # &quot;olleh&quot;</pre><h3>The Patterns to Remember</h3><p>After all of this, there are really just a handful of patterns doing all the heavy lifting:</p><ol><li><strong>Traversal</strong> — follow current = current.next until None</li><li><strong>Pointer Redirection</strong> — insert/delete by changing .next, no shifting</li><li><strong>Three-Variable Reverse</strong> — prev, current, next_node dance</li><li><strong>Slow/Fast Pointers</strong> — find middle, detect cycles</li><li><strong>Stack (LIFO)</strong> — brackets, undo systems, reversal</li></ol><h3>Common Mistakes to Avoid</h3><ul><li><strong>Not checking for </strong><strong>None</strong> — always guard against empty lists before traversing</li><li><strong>Losing the rest of the list when reversing</strong> — save next_node before flipping</li><li><strong>Forgetting the head edge case in delete</strong> — deleting the head needs special handling</li><li><strong>Infinite loops</strong> — always make sure you advance the pointer (current = current.next)</li><li><strong>Popping from an empty stack</strong> — check is_empty() before every pop()</li></ul><h3>Complexity Cheat Sheet</h3><pre>Operation -         Time -Space <br>Linked List Prepend  O(1) O(1)<br> Linked List Append  O(n) O(1)<br> Linked List Delete  O(n) O(1) <br>Linked List Reverse  O(n) O(1)<br> Find Middle         O(n) O(1) <br>Detect Cycle         O(n) O(1)<br> Stack push/pop/peek O(1) O(1) <br>Balanced Parentheses O(n) O(n)</pre><h3>Wrapping Up</h3><p>Arrays and linked lists are two different philosophies. Arrays say <em>“let’s keep everything together.”</em> Linked lists say <em>“let’s stay flexible and just keep a path to follow.”</em> Neither is better — they solve different problems.</p><p>And stacks? They’re secretly everywhere. Every time you hit Ctrl+Z, every time a function calls another function, every time your browser goes back a page — there’s a stack working quietly behind the scenes.</p><p>Next up in this series: <strong>Queues, Deques, and Hash Tables</strong> — what happens when we need First-In, First-Out, and instant lookups?</p><p><em>I</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a02cdf9213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays and Strings]]></title>
            <link>https://medium.com/@navodaoshini/arrays-and-strings-ea9d2f69124b?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9d2f69124b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[arrays-and-strings]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 10:34:44 GMT</pubDate>
            <atom:updated>2026-04-19T10:34:44.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AExYhtZULQqCLj4vw6tAHA.png" /><figcaption>Arrays and Strings: The Foundation of Every Algorithm You’ll Ever Write</figcaption></figure><p>If you’ve ever wondered why some code runs instantly and other code freezes your browser tab ,the answer almost always comes down to how data is stored and how it’s accessed. That’s what data structures and algorithms are really about.</p><p>Arrays sit at the very bottom of that conversation. Before trees, graphs, dynamic programming, or any of the advanced stuff, there are arrays. And understanding them deeply, not just syntactically, is what separates developers who can solve problems from developers who can only recognize them.</p><h4>What an Array Actually Is</h4><p>An array is a contiguous block of memory. When you create one, your computer reserves a sequence of slots ,one right next to the other and each slot holds a value.</p><p>In Python, lists are dynamic arrays under the hood. They behave like arrays but can resize themselves automatically. The cost of that convenience is subtle, inserting an element in the middle of a list requires shifting every element after it one position to the right. That’s O(n). Deletion works the same way in reverse.</p><p>Here’s the operation cost breakdown you need to have memorized:</p><p><strong><em>OperationTime - Complexity</em></strong></p><p><em>Access by index- O(1)</em></p><p><em>Append to end- O(1) amortized</em></p><p><em>Insert at position- iO(n)</em></p><p><em>Delete at position- iO(n)</em></p><p><em>Search (unsorted)- O(n)</em></p><p><em>Search (sorted)- O(log n)</em></p><p>The word <em>amortized</em> on append is worth paying attention to. Most of the time, appending is O(1) because there’s space at the end. Occasionally, the array runs out of space, doubles in size, and copies everything over — that one operation is O(n). Averaged across many appends, the cost works out to O(1).</p><h4>How to Measure Efficiency: Big-O Notation</h4><p>Before going further into arrays, it’s worth being precise about how we measure algorithmic efficiency.</p><p>Big-O notation describes how the runtime of an algorithm <em>scales</em> as the input grows. It answers the question: if you double your data, what happens to the time it takes?</p><ul><li><strong>O(1)- </strong>Constant. Doesn’t matter how big the input is, the work is the same.</li><li><strong>O(log n)</strong> -Logarithmic. Each step eliminates half the remaining possibilities. Binary search works this way.</li><li><strong>O(n)-</strong>Linear. You touch every element once.</li><li><strong>O(n log n)- </strong>Linearithmic. Efficient sorting algorithms like merge sort land here.</li><li><strong>O(n²)- </strong>Quadratic. Usually means nested loops over the same data. This is where things start to get slow.</li></ul><p>To make this concrete: for an array of 1,000 elements, O(n²) means up to 1,000,000 operations. For 10,000 elements, that becomes 100,000,000. This is why nested loops are worth avoiding and worth recognizing.</p><p>There’s also <em>space complexity</em> — how much extra memory an algorithm uses beyond the input itself. An algorithm that solves a problem using only a handful of variables has O(1) space complexity. One that creates a dictionary or second array proportional to the input is O(n).</p><h4>In-Place Manipulation</h4><p>One of the most important skills in array-based problem solving is manipulating data <em>in-place</em> — modifying the existing array without allocating a new one. This is O(1) space, and it’s the difference between a good solution and a great one in an interview context.</p><p>The key tool for in-place work is <strong>swapping</strong>: exchanging two elements directly in the array without needing a temporary structure.</p><p>In Python, this is beautifully simple:</p><pre>arr[left], arr[right] = arr[right], arr[left]</pre><p>Two patterns dominate in-place array manipulation.</p><h4>The Two-Pointer Technique</h4><p>Place one pointer at the start and another at the end. Move them toward each other based on some condition. This single idea solves an entire family of problems.</p><p>Array reversal is the clearest example:</p><pre>def reverse_array(arr):<br>    left, right = 0, len(arr) - 1<br>    while left &lt; right:<br>        arr[left], arr[right] = arr[right], arr[left]<br>        left += 1<br>        right -= 1<br>    return arr</pre><p>Time: O(n). Space: O(1). No second array created, no extra memory allocated.</p><p>The same two-pointer structure handles palindrome checking on strings:</p><pre>def is_palindrome(word):<br>    left, right = 0, len(word) - 1<br>    while left &lt; right:<br>        if word[left] != word[right]:<br>            return False<br>        left += 1<br>        right -= 1<br>    return True</pre><p>A word is a palindrome if it reads the same forwards and backwards. Rather than reversing the string and comparing, two pointers let you check this in a single O(n) pass with constant space.</p><h4>The Read/Write Pointer Pattern</h4><p>Sometimes you need to filter or compress an array in-place. The read/write approach uses two pointers moving in the <em>same</em> direction — one scanning, one writing.</p><p>Removing duplicates from a sorted array illustrates this cleanly:</p><pre>def remove_duplicates(arr):<br>    if not arr:<br>        return 0<br>    write = 1<br>    for read in range(1, len(arr)):<br>        if arr[read] != arr[write - 1]:<br>            arr[write] = arr[read]<br>            write += 1<br>    return write</pre><p>The same pattern handles moving zeros to the end of an array while preserving the relative order of non-zero elements.</p><h3>Hash Maps: Turning O(n²) into O(n)</h3><p>Nested loops are the most common source of inefficiency in early algorithm implementations. The pattern usually looks like: for each element, scan through all other elements to find a match.</p><p>Hash maps break this pattern. Instead of scanning, you store what you’ve already seen in a dictionary and look things up in O(1) time.</p><p><strong>Two Sum</strong> is the canonical example. Given an array and a target, find two numbers that add up to it.</p><p>The brute force approach checks every pair — O(n²). The hash map approach does it in a single pass — O(n):</p><pre>def two_sum(arr, target):<br>    num_dict = {}<br>    for i, num in enumerate(arr):<br>        complement = target - num<br>        if complement in num_dict:<br>            return [num_dict[complement], i]<br>        num_dict[num] = i<br>    return []</pre><p>For each number, you calculate what its complement would need to be, then check if you’ve already seen that complement. If yes, you’re done. If no, store the current number and move on. One pass, O(n) time, O(n) space.</p><p>This time-space trade-off — using a dictionary to avoid a second loop — appears in dozens of interview problems. Anagram detection, frequency counting, detecting duplicates, grouping by value. The underlying pattern is always the same: store what you’ve seen, look up what you need.</p><h3>Strings as Character Arrays</h3><p>In most languages, strings behave like read-only arrays of characters. The same algorithmic patterns apply — two pointers, frequency maps, sliding windows — but with one important constraint in Python: <strong>strings are immutable</strong>.</p><pre>chars = list(s)<br>chars[0] = &#39;H&#39;<br>s = &#39;&#39;.join(chars)</pre><p>There’s also a performance trap worth knowing. For n characters, this is O(n²) total work:</p><pre># Slow — O(n²)<br>result = &quot;&quot;<br>for char in chars:<br>    result += char<br><br>#The correct approach collects into a list and joins once at the end — O(n):<br># Fast — O(n)<br>result = &#39;&#39;.join(chars)<br></pre><p>This distinction matters at scale. For short strings the difference is invisible. For large inputs — think processing a large file character by character — it’s the difference between code that works and code that doesn’t.</p><h3>Kadane’s Algorithm: A Case Study in Elegant Thinking</h3><p>Maximum subarray is worth examining not just because it appears frequently, but because the solution demonstrates a particular style of algorithmic thinking.</p><p>The problem: given an array of numbers (some possibly negative), find the contiguous subarray with the largest sum.</p><p>A brute force solution checks every possible subarray — O(n²) or O(n³). Kadane’s algorithm solves it in O(n) with O(1) space by asking, at every position, a single question: is it better to extend the current subarray, or start fresh here?</p><pre>def max_subarray(nums):<br>    current_sum = nums[0]<br>    max_sum = nums[0]<br><br>    for i in range(1, len(nums)):<br>        current_sum = max(nums[i], current_sum + nums[i])<br>        max_sum = max(max_sum, current_sum)<br><br>    return max_sum</pre><p>This is dynamic programming in its simplest form-breaking a problem into overlapping subproblems and making locally optimal decisions that lead to a globally optimal result.</p><p>Arrays are the foundation because almost everything else is built on top of them. Stacks are arrays with restricted access. Queues are arrays with two ends. Hash tables use arrays internally for storage. Heaps are arrays interpreted as trees.</p><p>The patterns covered here -two pointers, read/write, hash maps, prefix sums, Kadane’s -appear across a wide range of problems far beyond simple arrays. They show up in linked lists, trees, and graphs, adapted to different structures. Learning them here, in their simplest context, is what makes them available to you later.</p><p>thank u for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9d2f69124b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hooks]]></title>
            <link>https://medium.com/@navodaoshini/react-custom-hooks-368d025649e7?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/368d025649e7</guid>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[custom-react-hook]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 14:21:19 GMT</pubDate>
            <atom:updated>2026-04-10T14:21:19.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25Jgu089QxXy72LiHpbicA.png" /><figcaption><strong>React Custom Hooks</strong></figcaption></figure><p>In this article, I’m going to explain what custom hooks are, why they exist, how to build one from scratch, and when to actually use them with real code examples along the way.</p><h3>1. What is a Hook?</h3><p>Before we go to custom hooks let’s talk about hooks. A hook is a special function that React gives you to add features to your components , like remembering a value, running code at certain times, or accessing the DOM. Without hooks, components couldn’t remember anything. Every re-render would wipe everything clean. Hooks solve that. React gives us built in hooks like usestate,useEfffect,useContext and useRef. These hooks are very useful.But what if we need the same hook logic in multiple components? That&#39;s where Custom hooks come in..Instead of copy-pasting the hook everywhere we can make a custom hook.</p><h3>2. So what is a Custom Hook?</h3><p>Simply, a custom hook is a JavaScript function that starts with use and uses other hooks inside it.</p><blockquote>“A custom hook is just a function that starts with use - and it can contain any hook logic you want to reuse.”</blockquote><blockquote>“A reusable JavaScript function that encapsulates stateful logic so it can<br>be shared across multiple components”</blockquote><p>So how do we name the custom hooks..First of all it must start with use.For example, useFetch.File name should start with use as well..like useFetch.js. Othervise react wont be able to recognize it as a hook.</p><p>Here are some popular real-world examples of custom hooks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqkunyHNb3Nr6372YPn_bQ.png" /></figure><h4>Rules of hooks</h4><p>Custom hooks still follow React’s rules- these apply to all hooks, built-in or custom:</p><ul><li>Only call hooks at the top level of a function — never inside loops, conditions, or nested functions</li><li>Only call hooks inside React function components or other custom hooks</li><li>React uses the useprefix to track and enforce these rules — that’s why naming matters</li></ul><h3>3. Why do custom hooks exist?</h3><p>The core reason is avoiding duplication. When the same stateful logic appears in multiple components, you have a choice: copy-paste it everywhere, or extract it once into a custom hook. The second option means bugs are fixed in one place, logic is easier to test, and components stay clean and focused on rendering.Let’s understand this concept with several examples.</p><h4>3.1 . useCounter</h4><p>Let’s understand this concept with useCounter exsample..</p><p>this is how we normaly do the count.</p><pre>import React, { useState } from &quot;react&quot;;<br><br>export default function Counter() {<br>  const [count, setCount] = useState(0); //we use useState here..we can only use t here.<br><br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  const decrement = () =&gt; {<br>    setCount(count - 1);<br>  };<br><br>  return (<br>    &lt;div style={{ textAlign: &quot;center&quot;, marginTop: &quot;50px&quot; }}&gt;<br>      &lt;h2&gt;Counter: {count}&lt;/h2&gt;<br><br>      &lt;button onClick={increment} style={{ marginRight: &quot;10px&quot; }}&gt;<br>        Increment<br>      &lt;/button&gt;<br><br>      &lt;button onClick={decrement}&gt;<br>        Decrement<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now let’s see how we do the same thing with using our custom hook. we can use a new folder called hooks under the src folder and put useCounter.js there.</p><pre>import { useState } from &quot;react&quot;;<br><br>export default function useCounter(initial) {<br>  const [count, setCount] = useState(initial);<br><br>  const increment = () =&gt; setCount((c) =&gt; c + 1);<br>  const decrement = () =&gt; setCount((c) =&gt; c - 1);<br><br>  return { count, increment, decrement };<br>}</pre><p>Now we can use our custom hook in our components.</p><pre>import useCounter from &quot;../hooks/useCounter&quot;; //we import the custom hook<br><br>function Counter() {<br>  const { count, increment, decrement } = useCounter(5);//in here we are using our custom hook<br>  return (<br>    &lt;div&gt;<br>      &lt;h5&gt;Customer Hook-usecounter&lt;/h5&gt;<br>      &lt;h2&gt;Count : {count}&lt;/h2&gt;<br>      &lt;button onClick={increment}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>    <br>  );<br>}<br><br>export default Counter;</pre><p>now let’s go to another example to understand this better..</p><h4>3.2 . useLocalStorage</h4><p>This hook lets any component persist state to the browser’s localStorage, so values survive page refreshes. Place it in src/hooks/useLocalStorage.js:</p><pre>//useLocalStorage.js<br><br>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function useLocalStorage(key, initial) {<br>  const [value, setValue] = useState(() =&gt; {<br>    const stored = localStorage.getItem(key);<br>    return stored ? JSON.parse(stored) : initial;<br>  });<br><br>  useEffect(() =&gt; {<br>    localStorage.setItem(key, JSON.stringify(value));<br>  }, [key, value]);<br><br>  return [value, setValue];<br>}</pre><pre>import React from &quot;react&quot;;<br>import useLocalStorage from &quot;../hooks/useLocalStorage&quot;;<br><br>function NameInput() {<br>  const [name, setName] = useLocalStorage(&quot;name&quot;, &quot;&quot;); //this is where we appy our custom hook<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h6&gt;Customer Hook-LocalStorage&lt;/h6&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;enter the name&quot;<br>        onChange={(e) =&gt; setName(e.target.value)}<br>      /&gt;<br>      &lt;h4&gt;Entered name is: {name}&lt;/h4&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default NameInput;</pre><h4>3.3. A Visual Example: fetching data from an API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oh3yXptawZFCqNQ-MKWi2A.png" /></figure><p>When we build an application, we have several pages like home, profile, about, settings, etc. Now all four need to fetch data from API.</p><p>What we normally do is write this below code in every single component.</p><p>this way the same useState and useEffect will be copy paste in every file..so if there was an error we have to fix it everywhere..But if we use custom hooks we will be able to prevent this problem.</p><pre>//Home.jsx<br>import { useState, useEffect } from &#39;react&#39;;<br><br>function Home() {<br>  const [data, setData] = useState(null);   // this code is repeated in every component<br><br>  useEffect(() =&gt; {                           // this one also wil be repeted<br>    fetch(&quot;https://jsonplaceholder.typicode.com/todos&quot;)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; setData(data));<br>  }, []);<br><br>  return &lt;p&gt;{data?.[0]?.title}&lt;/p&gt;;<br>}</pre><p>So let’s make useFetch..Means we will extract the fetch logic into a custom hooks.we can use hooks folder and put useFetch.js there.</p><pre>//useFetch.js<br><br>import { useState, useEffect } from &quot;react&quot;;<br><br>const useFetch = (url) =&gt; {<br>  const [data, setData]       = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError]     = useState(null);<br><br>  useEffect(() =&gt; {<br>    setLoading(true);  // this show loading whenever url changes<br><br>    fetch(url)<br>      .then((res) =&gt; {<br>        if (!res.ok) throw new Error(&quot;Something went wrong&quot;);<br>        return res.json();<br>      })<br>      .then((json) =&gt; {<br>        setData(json);<br>        setLoading(false);<br>      })<br>      .catch((err) =&gt; {<br>        setError(err.message);<br>        setLoading(false);<br>      });<br>  }, [url]); // re-runs every time the URL changes<br><br>  return { data, loading, error };<br>};<br><br>export default useFetch;</pre><p>Now we can use our custom hook in our components.</p><pre>//home.jsx<br><br>import useFetch from &quot;./hooks/useFetch&quot;;<br><br>function Home() {<br>  const { data, loading, error } = useFetch(<br>    &quot;https://jsonplaceholder.typicode.com/todos?_limit=5&quot;<br>  );<br><br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error)   return &lt;p&gt;Error: {error}&lt;/p&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map((item) =&gt; (<br>        &lt;li key={item.id}&gt;<br>          {item.completed ? &quot;done&quot; : &quot;pending&quot;} {item.title}<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>export default Home;</pre><pre>//profile.jsx<br>import useFetch from &quot;./hooks/useFetch&quot;;<br><br>function Profile() {<br>  const { data, loading, error } = useFetch(<br>    &quot;https://jsonplaceholder.typicode.com/users/1&quot;<br>  );<br><br>  if (loading) return &lt;p&gt;Loading profile...&lt;/p&gt;;<br>  if (error)   return &lt;p&gt;Error: {error}&lt;/p&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{data.name}&lt;/h2&gt;<br>      &lt;p&gt;Email: {data.email}&lt;/p&gt;<br>      &lt;p&gt;Website: {data.website}&lt;/p&gt;<br>      &lt;p&gt;Phone: {data.phone}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Profile;</pre><h3>4. When not to use a custom hook?</h3><p>Custom hooks are not always the right tool. If the logic is only used in one component and is unlikely to be reused, keep it inline. The overhead of creating and importing a separate file isn’t worth it for logic that lives in exactly one place.</p><h3>5. Summary</h3><p>Custom hooks are one of React’s most powerful patterns — not because they do anything new, but because they let you organise what you already know. Instead of scattering the same useState and useEffect logic across multiple files, you write it once, name it clearly, and reuse it everywhere.</p><p>Thank u for reading!</p><p>_________________________________________________________________</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=368d025649e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS FlexBox and Grid Layout]]></title>
            <link>https://medium.com/@navodaoshini/css-flexbox-and-grid-layout-5485c97e664e?source=rss-1b28c8b6d2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5485c97e664e</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-grid]]></category>
            <category><![CDATA[flexbox]]></category>
            <dc:creator><![CDATA[Osini Navoda]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 05:11:04 GMT</pubDate>
            <atom:updated>2026-02-07T09:19:57.418Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>First of all lets see what are those..What they do…</strong></p><p>In the early days of web development, creating responsive, clean layouts meant wrestling with floats, clearfixes, and absolute positioning. Often resulting in fragile, hard-to-maintain code. But thanks to CSS layout modules like Flexbox and Grid, we now have intuitive, robust tools to build beautiful interfaces for any screen size.</p><blockquote>“Flexbox is essentially for laying out items in a single dimension — in a row OR a column. Grid is for the layout of items in two dimensions — rows AND columns.” (Rachel Andrew)</blockquote><h3><strong>Let’s go through CSS FlexBox first!</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTE25oDymaJaZujMhUfwMQ.png" /></figure><blockquote>CSS Flexbox (Flexible Box Layout) is a <strong>one-dimensional layout model</strong> for arranging items in rows or columns, designed for efficient alignment, spacing, and distribution of space within a container. It simplifies complex layouts and vertical centering that were previously difficult with traditional CSS methods.(W3Schools)</blockquote><h4>Basic Flexbox Syntax</h4><p>display: flex;<br> flex-direction: row; <br> justify-content: center; <br> align-items: center;<br> flex-wrap: wrap;</p><h4><strong>first let’s see the attributes of Parent.</strong></h4><p>display<br>Turns an element into a flex container so its children become flex items.</p><p>flex-direction<br>Sets the main direction of the layout: row (left to right), row-reverse, column (top to bottom), or column-reverse.</p><p>justify-content<br>Aligns flex items along the main axis (e.g., left/right if row, top/bottom if column). Common values: flex-start, center, space in between</p><p>align-items<br>Aligns flex items along the cross axis (e.g., top/bottom if row, left/right if column). Like vertical centering in a horizontal row.</p><p>align-content<br>Controls spacing between lines of items when there’s extra space and multiple lines (only matters when flex-wrap: wrap is used).</p><p>flex-wrap<br>Decides whether items stay in one line or wrap onto multiple lines if they don’t fit.</p><p>gap<br>Adds space between flex items (just like in Grid). Works in modern browsers.</p><h4>Attributes of childern(items)</h4><p>flex<br>Shorthand to control how much an item grows, shrinks, and its initial size. Often used as flex:1 to make items share space equally.</p><p>align-self<br>Overrides align-itemsfor a single item—let’s one item align differently from the rest.</p><p>order<br>Changes the visual order of an item (default is 0). Higher numbers appear later.</p><h4>You can see example code and output here</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*Kj7_ImBvnaurAvotJlETZA.png" /><figcaption>code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*snFJ8ORpyBX9YcgNUuPA9g.png" /><figcaption>output</figcaption></figure><h3>Now let’s go to Grid Layout!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*8FFwimnXY1dvzjxX.png" /></figure><blockquote>“The Grid Layout Module offers a grid-based layout system, with rows and columns. It makes it easy to design responsive structures without using float or positioning.”</blockquote><p>CSS Grid is a two-dimensional layout system — you control both rows and columns simultaneously. This makes it perfect for overall page layouts, dashboards, image galleries, or magazine-style designs.</p><h4>Basic Grid Syntax</h4><p>display: grid;</p><p>grid-template-columns: 1fr 2fr 1fr; — three columns</p><p>grid-template-rows: 150px 100px; — means 2 rows</p><p>gap: 20px; — space between cells</p><p>fr means fraction unit — divides available space proportionally.</p><p><strong>The parent is the organizer. It is the container that holds our items. Let&#39;s see what kind of attributes we can use in here.</strong></p><p>Parent = The boss of the layout. Sets rows, columns, gaps, and default alignment.</p><p>grid-template-columns<br>Defines the number of columns in a grid and how wide each column is.</p><p>grid-template-rows<br>Defines the height of rows in the grid.</p><p>gap<br>Controls the space between rows and columns in the grid.</p><p>justify-items<br>Aligns items horizontally inside their grid cells.</p><p>align-items<br>Aligns items vertically inside their grid cells.</p><p>place-items<br>A shorthand property to align items both horizontally and vertically at once.</p><p>grid-template-areas<br>Allows naming different sections of the grid and placing items into those named areas.</p><p><strong>The items that are inside the grids are called child components.</strong></p><p>Items = The kids. Usually follow the plan, but can ask for special spots or alignment.</p><p>now lets see their attributes as well.</p><p>grid-column<br>Controls which columns a grid item starts and ends in.</p><p>grid-row<br>Controls which rows a grid item starts and ends in.</p><p>grid-area<br>Places an item into a named area defined in the parent grid.</p><p>justify-self<br>Aligns a single grid item horizontally inside its own cell.</p><p>align-self<br>Aligns a single grid item vertically inside its own cell.</p><p>place-self<br>A shorthand to align a single item both horizontally and vertically at once.</p><h4>Here is a code example and output.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*uvY14lwmRY8bkZHx0ZqwOQ.png" /><figcaption>code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PnKvveilIHg5m0ge1aZufQ.png" /><figcaption>output</figcaption></figure><h3>Now let&#39;s see their differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HY2DXdU_kQT4FvdxiuKcrQ.png" /></figure><h3>Also here is how we use both in Responsiveness</h3><p><strong>Flexbox</strong></p><p>.box1{<br> flex-direction: column;<br>}</p><p><a href="http://twitter.com/media">@media</a> (min-width: 768px) {<br> .box1 {<br> flex-direction: row;<br> }<br>}</p><p><strong>Grid</strong></p><p>.grid-layout {<br> grid-template-columns: 1fr; <br>}</p><p><a href="http://twitter.com/media">@media</a> (min-width: 768px) {<br> grid-template-columns: 200px 1fr 200px; <br>}</p><p>Now you have seen how you can use both flexbox and the grid.</p><p>Use Flexbox when you’re arranging items in one direction: a navigation bar, a set of buttons, a card list, or a vertically centered hero section. It’s simple, lightweight, and perfect for component-level layouts.</p><p>Use CSS Grid when you need full control over both rows and columns: a dashboard, a photo gallery, a magazine homepage, or an app layout with a header, sidebar, main content, and footer. It’s your go-to for page-level architecture.</p><p>In modern web development, they can work together.A Grid cell can contain a Flex container. A Flex item can be a Grid itself.</p><h4>you can also use these tools.</h4><p>Firefox Grid Inspector</p><p>Online CSS Grid generators</p><p>MDN and W3Schools</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5485c97e664e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>