<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Bvnkumar</title>
    <description>The latest articles on Forem by Bvnkumar (@bvnkumar).</description>
    <link>https://forem.com/bvnkumar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F633674%2F7b2b9592-de9c-4c45-b8db-11c0b84a09b9.jpeg</url>
      <title>Forem: Bvnkumar</title>
      <link>https://forem.com/bvnkumar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bvnkumar"/>
    <language>en</language>
    <item>
      <title>LRU (Least Recently Used) Cache Data Structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Tue, 22 Oct 2024 04:01:27 +0000</pubDate>
      <link>https://forem.com/bvnkumar/lru-least-recently-used-cache-data-structure-3276</link>
      <guid>https://forem.com/bvnkumar/lru-least-recently-used-cache-data-structure-3276</guid>
      <description>&lt;p&gt;LRU (Least Recently Used) Cache is a type of cache that evicts the least recently accessed item when the cache exceeds its capacity. It's useful in scenarios where memory is limited, and you want to cache only the most frequently accessed data.&lt;/p&gt;

&lt;p&gt;In JavaScript, an LRU Cache can be implemented using a combination of a Map (for fast lookups and maintaining insertion order) and a Doubly Linked List (for efficient insertions and deletions at both ends). However, for simplicity, we'll use a Map in the following implementation.&lt;/p&gt;

&lt;p&gt;Here’s a JavaScript implementation of an LRU Cache:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LRUCache {
    constructor(capacity) {
        this.capacity = capacity;
        this.cache = new Map(); // Using Map to maintain key-value pairs
    }
    // Get the value from the cache
    get(key) {
        if (!this.cache.has(key)) {
            return -1; // If the key is not found, return -1
        }

        // Key is found, move the key to the most recent position
        const value = this.cache.get(key);
        this.cache.delete(key); // Remove the old entry
        this.cache.set(key, value); // Reinsert to update its position (most recently used)

        return value;
    }

    // Add or update the value in the cache
    put(key, value) {
        if (this.cache.has(key)) {
            // If the key already exists, remove it to update its position
            this.cache.delete(key);
        } else if (this.cache.size &amp;gt;= this.capacity) {
            // If the cache is at capacity, delete the least recently used item
            const leastRecentlyUsedKey = this.cache.keys().next().value;
            this.cache.delete(leastRecentlyUsedKey);
        }

        // Insert the new key-value pair (most recent)
        this.cache.set(key, value);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;br&gt;
Constructor: The LRUCache class is initialized with a given capacity, and it uses a Map to store the cached key-value pairs. The Map keeps track of the insertion order, which helps identify the least recently used (LRU) item.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;get(key):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the key exists in the cache, the method returns its value and moves the key to the most recent position by first deleting the key and then reinserting it.&lt;/li&gt;
&lt;li&gt;If the key doesn't exist, it returns -1.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;put(key, value):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the key already exists in the cache, it removes the key and reinserts it (updating its position as the most recently used).&lt;/li&gt;
&lt;li&gt;If the cache reaches its capacity, it removes the least recently used key (the first one in the Map).&lt;/li&gt;
&lt;li&gt;Finally, the new key-value pair is added to the cache.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Usage Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const lruCache = new LRUCache(3); // Cache with a capacity of 3

lruCache.put(1, 'one');   // Add key 1
lruCache.put(2, 'two');   // Add key 2
lruCache.put(3, 'three'); // Add key 3

console.log(lruCache.get(1)); // Output: 'one' (key 1 becomes the most recently used)

lruCache.put(4, 'four'); // Cache is full, so it evicts key 2 (least recently used)

console.log(lruCache.get(2)); // Output: -1 (key 2 has been evicted)
console.log(lruCache.get(3)); // Output: 'three' (key 3 is still in the cache)
console.log(lruCache.get(4)); // Output: 'four' (key 4 is in the cache)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Observer Design Pattern using Javascript</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Mon, 27 Mar 2023 23:27:29 +0000</pubDate>
      <link>https://forem.com/bvnkumar/observer-pattern-using-javascript-1nh3</link>
      <guid>https://forem.com/bvnkumar/observer-pattern-using-javascript-1nh3</guid>
      <description>&lt;p&gt;Design patterns are used to solve the specific problems in the software. Today we will be discussed about &lt;strong&gt;Observer Pattern&lt;/strong&gt; in javascript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Observer pattern&lt;/strong&gt; is a software design pattern in which an object, called subject, maintains a list of its dependencies called observers and notify them automatically of any state changes.&lt;/p&gt;

&lt;p&gt;For Example, In react if state changes then components will re-render accordingly. this process is similar to observer pattern functionality.&lt;/p&gt;

&lt;p&gt;Below is the sample program for observer pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function Subject(){
  this.obeservers=[];
}

Subject.prototype={
  add:function(fn){
    this.obeservers.push(fn)
  },
  remove:function(fn){
    this.obeservers=this.obeservers.filter(fun=&amp;gt;f!=fn)
  },
  notify:function(){
    this.obeservers.forEach(fun=&amp;gt;{
      fun.call()
    })
  }
}
function observer1(){
  console.log("in the observer1")
}
function observer2(){
  console.log("in the observer2")
}
const subject=new Subject();
subject.add(observer1);
subject.add(observer2);
subject.notify() // It will loop through all the observers.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we have created the Subject constructor function. And it has observers list property, add, delete and notify methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Observers&lt;/strong&gt;: It will have no.of observers.&lt;br&gt;
&lt;strong&gt;Add&lt;/strong&gt;: It will add observers(functions) to that list.&lt;br&gt;
&lt;strong&gt;Remove&lt;/strong&gt;: this method will remove the function from the list based on its argument.&lt;br&gt;
&lt;strong&gt;Notify&lt;/strong&gt;: this will notify all the observers in the list.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Comments and suggestions are always welcome.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>designpatterns</category>
      <category>programming</category>
    </item>
    <item>
      <title>Javascript Factory Design Pattern</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Mon, 20 Mar 2023 20:58:11 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-factory-design-pattern-31n4</link>
      <guid>https://forem.com/bvnkumar/javascript-factory-design-pattern-31n4</guid>
      <description>&lt;p&gt;Design patterns are templates or solutions for common software development problems.&lt;/p&gt;

&lt;p&gt;Design patterns are divided into three categories.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Behavioral &lt;/li&gt;
&lt;li&gt;Creational&lt;/li&gt;
&lt;li&gt;Structural&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The factory pattern is a creational design pattern that provides a generic interface for creating objects.&lt;/p&gt;

&lt;p&gt;EX:-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Developer(name , experience) {
    this.name = name;
    this.type = "Developer";
    this.experience = experience;
}
function Tester(name, experience) {
    this.name = name;
    this.type = "Tester";
    this.experience = experience;
}
function EmployeeFactory() {
    this.create = (name, type) =&amp;gt; {
        switch (type) {
            case 1:
                return new Developer(name,4);
                break;
            case 2:
                return new Tester(name,6);
                break;
        }
    }
}

function say() {
    console.log("i am " + this.name + " i am a " + this.type +" and having a "+ this.experience +"years of experience ");
}

let employees = [];
const employeeFactory = new EmployeeFactory();
employees.push(employeeFactory.create("Sam", 1));
employees.forEach((employee) =&amp;gt; {
    say.call(employee);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we have created developer and Tester objects with their names. Using this pattern you could create as many objects you require each with their own name and experience.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>designpatterns</category>
      <category>factory</category>
      <category>programming</category>
    </item>
    <item>
      <title>Longest string without repeating characters in javaascript</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Tue, 07 Jun 2022 00:52:01 +0000</pubDate>
      <link>https://forem.com/bvnkumar/longest-string-without-repeating-characters-150k</link>
      <guid>https://forem.com/bvnkumar/longest-string-without-repeating-characters-150k</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  let map = new Map();
    if (!s.length) {
        return null
    }
    for (let i = 0; i &amp;lt; s.length; i++) {
        let count = 0;
        let checkString = s.substring(0, i + 1)
        let start = 0;
        while (s.substring(start, s.length - 1).indexOf(checkString) &amp;gt; -1) {
            count++;
            if (map.has(checkString)) {
                let existedCount = map.get(checkString);
                map.set(checkString, existedCount + 1)
                existedCount = 0;
            } else {
                map.set(checkString, count)
            }
            start++;
        }
    }
    if (map.size) {
        let keys = Array.from(map.keys());
        return keys.reduce((a, b) =&amp;gt; map.get(a) &amp;gt; map.get(b) ? map.get(a) : map.get(b))
    }
};
//console.log("Higest", lengthOfLongestSubstring('abcabcbb'))
//console.log("map", map)`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Any suggestions or comments are welcome.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>string</category>
      <category>programming</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Print left view of binary tree</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Tue, 24 May 2022 02:40:50 +0000</pubDate>
      <link>https://forem.com/bvnkumar/print-left-view-of-binary-tree-554g</link>
      <guid>https://forem.com/bvnkumar/print-left-view-of-binary-tree-554g</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node{
  constructor(data,left,right){
    this.data=data;
    this.left=left;
    this.right=right;
  }
}

const tree=new Node(10);
tree.left=new Node(1)
tree.right=new Node(3)
tree.left.left=new Node(4)
tree.left.right=new Node(5)
tree.right.right=new Node(6)
tree.right.left=new Node(2);
tree.right.right.left=new Node(7)
tree.left.right.left=new Node(8)
tree.left.right.right=new Node(9)
tree.left.right.left.left=new Node(10);

let max_level=0;
function leftsideView(node,level){
  if(node==null){
    return null;
  }
  if(max_level&amp;lt;level){
    console.log(node.data)
    max_level=level;
  }
  leftsideView(node.left,level+1);
  leftsideView(node.right,level+1);
}
leftsideView(tree,1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>programming</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Binary search algorithm implementation in JavaScript</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Fri, 13 May 2022 03:01:31 +0000</pubDate>
      <link>https://forem.com/bvnkumar/binary-search-javascript-algorithm-9j9</link>
      <guid>https://forem.com/bvnkumar/binary-search-javascript-algorithm-9j9</guid>
      <description>&lt;p&gt;Mastering Binary Search: The Efficient Way to Find Elements in a Sorted Array&lt;/p&gt;

&lt;p&gt;Binary Search is a powerful algorithm based on the divide-and-conquer approach, allowing us to search elements efficiently in a sorted array. Compared to a linear search, which has a time complexity of O(n), binary search significantly reduces the search time to O(log n) by halving the search space at each step.&lt;/p&gt;

&lt;p&gt;Key Features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Works only on sorted arrays.&lt;/li&gt;
&lt;li&gt;Much faster than linear search due to its logarithmic time complexity.&lt;/li&gt;
&lt;li&gt;Splits the search space in half with each iteration, narrowing down the target efficiently.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function binarySearch(list, item, left, right) {
    let mid = Math.floor((left + right) / 2)
    if (left &amp;gt; right) {
        return false
    }

    // If the midpoint is the item we're looking for, return true.
    if (list[mid] == item) {
        return true;
    } else if (item &amp;lt; list[mid]) {

    // If the item is smaller than the midpoint, search the left half.
      return binarySearch(list, item, left, mid - 1)

    } else {

    // Otherwise, search the right half
        return binarySearch(list, item, mid + 1, right)
    }
}

let list=[1,2,3,5,6,7,8,9];
console.log(binarySearch(list,10,0,list.length-1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why is Binary Search Fast?
&lt;/h2&gt;

&lt;p&gt;Because it halves the search space with each comparison. For an array of 1000 elements, instead of checking each one, binary search only takes about 10 checks (log₂(1000) ≈ 10), making it much faster for large datasets.&lt;/p&gt;

&lt;p&gt;Example Walkthrough:&lt;br&gt;
Let's say you want to search for the number 5 in the array [1, 2, 3, 5, 6, 7, 8, 9].&lt;/p&gt;

&lt;p&gt;Step 1: Start with left = 0, right = 7. Calculate mid = (0 + 7) / 2 = 3.&lt;br&gt;
list[mid] is 5, which is our target, so return true.&lt;br&gt;
This simple, efficient process allows us to find the element quickly.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Feel free to drop your thoughts or suggestions on how to improve the algorithm further! 👇&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>binarysearch</category>
      <category>javascript</category>
      <category>algorithms</category>
      <category>programming</category>
    </item>
    <item>
      <title>Javascript Binary heap data structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Mon, 09 May 2022 00:58:51 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-binary-heap-data-structure-1d9l</link>
      <guid>https://forem.com/bvnkumar/javascript-binary-heap-data-structure-1d9l</guid>
      <description>&lt;p&gt;&lt;strong&gt;Binary heap&lt;/strong&gt;:- A binary heap is a complete binary tree which satisfies the heap ordering property. The ordering can be one of two types:&lt;/p&gt;

&lt;p&gt;the &lt;u&gt;&lt;em&gt;min-heap&lt;/em&gt;&lt;/u&gt; property: the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root.&lt;br&gt;
the &lt;u&gt;&lt;em&gt;max-heap&lt;/em&gt;&lt;/u&gt; property: the value of each node is less than or equal to the value of its parent, with the maximum-value element at the root.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let MinHeap = function() {
    let head = [null];
    this.insert = function(element) {
        head.push(element);
        if (head.length &amp;gt; 2) {
            let idx = head.length - 1;
            while (head[idx] &amp;lt; head[Math.floor(idx / 2)]) {
                if (idx &amp;gt;= 1) {
                    [head[Math.floor(idx / 2)], head[idx]] = [head[idx], head[Math.floor(idx / 2)]];
                    if (Math.floor(idx / 2) &amp;gt; 1) {
                        idx = Math.floor(idx / 2);
                    } else {
                        break;
                    }
                }
            }
        }
    }
}
let minHeap = new MinHeap();
minHeap.insert(2)
minHeap.insert(1)
minHeap.insert(3)
minHeap.insert(4)

let MaxHeap = function() {
    let head = [null];
    this.insert = function(element) {
        head.push(element);
        if (head.length &amp;gt; 2) {
            let idx = head.length - 1;
            while (head[idx] &amp;gt; head[Math.floor(idx / 2)]) {
                if (idx &amp;gt;= 1) {
                    [head[Math.floor(idx / 2)], head[idx]] = [head[idx], head[Math.floor(idx / 2)]];
                    if (Math.floor(idx / 2) &amp;gt; 1) {
                        idx = Math.floor(idx / 2);
                    } else {
                        break;
                    }
                }
            }
        }
    }
}
let maxHeap = new MaxHeap();
maxHeap.insert(2)
maxHeap.insert(1)
maxHeap.insert(3)
maxHeap.insert(4)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Any comments or suggestions are welcome.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>binaryheap</category>
    </item>
    <item>
      <title>Javascript Linked List data structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Tue, 26 Apr 2022 03:22:55 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-linked-list-data-structure-9k9</link>
      <guid>https://forem.com/bvnkumar/javascript-linked-list-data-structure-9k9</guid>
      <description>&lt;p&gt;&lt;strong&gt;LinkedList&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;A linked list is a linear data structure similar to an array. However, unlike arrays, elements are not stored in a particular memory location or index. Rather each element is a separate object that contains a pointer or a link to the next object in that list.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Nodes can easily be added or removed from a linked list without re-organizing the entire data structure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Search operations are slow in linked list over arrays, random access of data element is not allowed. Nodes are accessed sequentially from first node.&lt;/li&gt;
&lt;li&gt;It uses more memory than arrays because of storage of the pointer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Internal Design of linked list&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function LinkedList() {
    let length = 0;
    let head = null;
    const Node = function(element) {
        this.element = element;
        this.next = null;
    }
    this.size = function() {
        return length;
    }
    this.head = function() {
        return head;
    }
    this.add = function(element) {
        let node = new Node(element);
        if (head == null) {
            head = node;
        } else {
            let currentNode = head;
            while (currentNode.next) {
                currentNode = currentNode.next;
            }
            currentNode.next = node;
        }
        length++
    }

    this.remove = function(element) {
        let currentNode = head;
        let previousNode;
        if (currentNode.element == element) {
            head = currentNode.next;
        } else {
            while (currentNode.element !== element) {
                previousNode = currentNode;
                currentNode = currentNode.next;
            }
            previousNode.next = currentNode.next;
        }
        length--;
    }
    this.isEmpty = function() {
        return length == 0;
    }
    this.indexOf = function(element) {
        let currentNode = head;
        let index = -1;
        while (currentNode) {
            index++;
            if (currentNode.element == element) {
                return index;
            }
            currentNode = currentNode.next;
        }
        return -1;
    }
    this.elementAt = function(index) {
        let currentNode = head;
        let count = 0;
        while (count &amp;lt; index) {
            count++
            currentNode = currentNode.next;
        }
        return currentNode.element;
    }
}
var link = new LinkedList();
link.add("hello");
link.add("hello")
console.log(link)
console.log("elementAt", link.elementAt(0))
console.log("indexOf", link.indexOf("bye"))
link.remove("hello")
link.remove("hello")
console.log("isEmpty", link.isEmpty())
console.log("length", link.size())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Any comments or suggestions are welcome.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>linkedlist</category>
      <category>programming</category>
      <category>datastructure</category>
    </item>
    <item>
      <title>Javascript Binary Tree data structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Wed, 20 Apr 2022 04:01:09 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-binary-tree-data-structure-4hec</link>
      <guid>https://forem.com/bvnkumar/javascript-binary-tree-data-structure-4hec</guid>
      <description>&lt;p&gt;&lt;strong&gt;Binary Tree:&lt;/strong&gt;&lt;br&gt;
A binary tree is a data structure consisting of a set of linked nodes that represent a hierarchical tree structure. Each node is linked to others via parent child relationship.&lt;br&gt;
Any given node can have at most two children(left&amp;amp;right).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Internal structure of binary tree:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Node {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
}

class BST {
    constructor() {
        this.root = null;
    }
    add(data) {
        const node = this.root;
        if (node == null) {
            this.root = new Node(data);
        } else {
            const searchTree = function(data) {
                if (data &amp;lt; node.data) {
                    if (node.left == null) {
                        node.left = new Node(data);
                        return;
                    } else if (node.left != null) {
                        return searchTree(node.left)
                    }
                } else if (data &amp;gt; node.data) {
                    if (node.right == null) {
                        node.right = new Node(data)
                        return;
                    } else if (node.right != null) {
                        return searchTree(node.right)
                    }
                } else {
                    return null;
                }
            }
            return searchTree(data)
        }
    }
    findMax() {
        let current = this.root;
        while (current.right != null) {
            current = current.right;
        }
        return current.data;
    }
    findMin() {
        let current = this.root;
        while (current.left != null) {
            current = current.left
        }
        return current.data;
    }
    find(data) {
        let current = this.root;
        while (current.data != null) {
            if (data &amp;lt; current.data) {
                current = current.left;
            } else {
                current = current.right;
            }
            if (current == null) {
                return null;
            }
        }
        return current;
    }
    isPresent(data) {
        let current = this.root;
        while (current) {
            if (data == current.data) {
                return true
            }
            if (data &amp;lt; current.data) {
                current = current.left;
            } else {
                current = current.right;
            }
        }
        return false;
    }
}

const bst = new BST();
bst.add(1);
bst.add(2);
bst.add(3);
console.log(bst.findMin());
console.log(bst.findMax());
console.log(bst.find(1));
console.log(bst.isPresent(1));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Any comments or suggestions are welcome.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>binarytree</category>
      <category>datastructure</category>
      <category>programming</category>
    </item>
    <item>
      <title>Javascript Queue data structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Mon, 18 Apr 2022 18:23:18 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-queue-data-structure-1d20</link>
      <guid>https://forem.com/bvnkumar/javascript-queue-data-structure-1d20</guid>
      <description>&lt;p&gt;&lt;strong&gt;QUEUE&lt;/strong&gt;:&lt;br&gt;
Queue is also one type of data structure and works like a stack but it follows a first in first out(FIFO) order.&lt;br&gt;
Example: When you are in a line to pay a bill at the counter, we should follow the sequence like first in first out, queue also works same.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Internal design of queue:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Queue = function() {
    let collections = [];
    this.add = function(item) {
        return collections.push(item);
    }
    this.size = function() {
        return collections.length;
    }
    this.isEmpty = function() {
        retun(collections.length == 0)
    }
    this.enqueue = function(item) {
        return collections.push(item)
    }
    this.dequeue = function(item) {
        return collections.shift();
    }
    this.front = function() {
        return collections[0];
    }
}

let queue = new Queue();
console.log(queue.size())
queue.enqueue("1");
queue.enqueue("2");
console.log(queue.size())
console.log(queue.front());
queue.dequeue();
console.log(queue.size())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Any comments or suggestions are welcome.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>queue</category>
      <category>datastructure</category>
      <category>programming</category>
    </item>
    <item>
      <title>Javascript Set data structure</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Sun, 17 Apr 2022 13:40:37 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-set-data-structure-hfi</link>
      <guid>https://forem.com/bvnkumar/javascript-set-data-structure-hfi</guid>
      <description>&lt;p&gt;&lt;strong&gt;Set&lt;/strong&gt;: Set data structure allow to add data to a container.&lt;/p&gt;

&lt;p&gt;This custom Set implementation in JavaScript uses an array (collection[]) to store unique values, similar to the built-in Set object. It provides methods to add, remove, check, and retrieve the size of the collection while ensuring each element is unique.&lt;/p&gt;

&lt;p&gt;Methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;size(): Returns the number of elements in the set.&lt;/li&gt;
&lt;li&gt;has(item): Checks if the set contains a specific item.&lt;/li&gt;
&lt;li&gt;add(item): Adds a new item to the set if it doesn’t already exist.&lt;/li&gt;
&lt;li&gt;delete(item): Removes an item from the set if it exists.&lt;/li&gt;
&lt;li&gt;clear(): Removes all items from the set.&lt;/li&gt;
&lt;li&gt;values(): Returns all the items in the set.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is an example of set internal implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Set=function(){
  let collection=[];
  this.size=function(){
    return collection.length;
  }
  this.has=function(item){
   return collection.indexOf(item)!==-1
  }
  this.add=function(item){
    if(!this.has(item)){
      collection.push(item)
      return true;
    }
    return false;
  }
  this.delete=function(item){
    if(!this.has(item)){
      return false;
    }else{
      let index=collection.indexOf(item);
      collection.splice(index,1);
      return true;
    }
  }
  this.clear=function(){
    collection=[];
  }
  this.values=function(){
    return collection;
  }
}
let set=new Set();
console.log(set.size());
console.log(set.add(1));
console.log(set.add(2));
console.log(set.size());
console.log(set.delete(2));
console.log(set.delete(2));
console.log(set.size());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Time Complexity:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;size(): O(1) - Simply returns the length of the array.&lt;/li&gt;
&lt;li&gt;has(item): O(n) - The indexOf() method is used, which performs a linear search through the array.&lt;/li&gt;
&lt;li&gt;add(item): O(n) - Before adding, it calls has(item) which is O(n), and if the item doesn’t exist, push() is O(1).&lt;/li&gt;
&lt;li&gt;delete(item): O(n) - It uses indexOf() to find the index of the item, which is O(n), and then splice() to remove it, which is also O(n).&lt;/li&gt;
&lt;li&gt;clear(): O(1) - Just resets the array to an empty array.&lt;/li&gt;
&lt;li&gt;values(): O(1) - Returns the reference to the array.
&amp;gt; &lt;em&gt;Any comments or suggestions are welcome.&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>set</category>
      <category>datastructure</category>
      <category>programming</category>
    </item>
    <item>
      <title>Javascript Stack Data Structure.</title>
      <dc:creator>Bvnkumar</dc:creator>
      <pubDate>Sat, 16 Apr 2022 03:45:00 +0000</pubDate>
      <link>https://forem.com/bvnkumar/javascript-stack-data-structure-2b30</link>
      <guid>https://forem.com/bvnkumar/javascript-stack-data-structure-2b30</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Understanding JavaScript Call Stack and Stack Data Structure&lt;br&gt;
JavaScript is a single-threaded language, meaning it uses a single call stack to manage the execution context of functions.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Whenever a function is called, the JavaScript engine creates a global execution context and pushes it onto the call stack. When a new function is invoked, a function-specific execution context is added on top of the global one.&lt;br&gt;
The call stack follows the Last In, First Out (LIFO) order, meaning the most recent function added will be the first to be removed once it completes execution.&lt;br&gt;
Here's a simple example of a stack data structure implemented in JavaScript. You can execute this code in any JavaScript environment and observe the console output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Stack {
  constructor() {
    this.count = 0;
    this.storage = {};
  }

  size() {
    return this.count;
  }

  push(item) {
    this.storage[this.count] = item;
    this.count++;
  }

  peek() {
    return this.isEmpty() ? undefined : this.storage[this.count - 1];
  }

  pop() {
    if (this.isEmpty()) return undefined;
    this.count--;
    const result = this.storage[this.count];
    delete this.storage[this.count];
    return result;
  }

  isEmpty() {
    return this.count === 0;
  }
}

const stack = new Stack();
console.log(stack.size()); // 0
stack.push(1);
stack.push(2);
console.log(stack.peek()); // 2
console.log(stack.pop());  // 2
console.log(stack.size()); // 1

//Feel free to try it out and check the results!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;u&gt;&amp;gt; Breakdown of the time complexities:&lt;br&gt;
&lt;/u&gt;&lt;br&gt;
&lt;u&gt;Push (Adding an item): O(1)&lt;br&gt;
&lt;/u&gt;The push operation simply adds an item to the top of the stack, and this happens in constant time, since it involves a direct assignment and increment of a counter.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Pop (Removing the top item): O(1)&lt;br&gt;
&lt;/u&gt;Similarly, the pop operation just removes the item from the top of the stack, deletes the reference, and decrements the counter, all of which occur in constant time.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Peek (Retrieving the top item): O(1)&lt;br&gt;
&lt;/u&gt;The peek operation only accesses the top item without modifying the stack, so it's also constant time.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Size (Retrieving the stack size): O(1)&lt;br&gt;
&lt;/u&gt;Since the size of the stack is stored in a variable and updated with each push or pop, retrieving the size is a constant time operation.&lt;/p&gt;

&lt;p&gt;Thus, all the primary operations on a stack—push, pop, peek, and size—have a time complexity of O(1), making the stack a very efficient data structure for managing collections of items where only the top item is of interest.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Any comments or suggestions are welcome&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>datastructure</category>
      <category>stack</category>
      <category>callstack</category>
    </item>
  </channel>
</rss>
