Home

  • Starting #100DaysOfCode

    What exactly I will do during the 100 Days?

    • DSA – this will be my main focus during this 100 days for my interview preparation and will be doing LeetCode questions side-by-side. [Main resource: Coding Minutes DSA Course] and (Blind’s 75 List Qs/ Grokking Coding Interviews)
    • Web – One of my long term goal is to make useful things on the internet by building them in public (this is an attempt to that) for the people. So, I want to build meaningful things will indie-hacking.

    Some Techniques

    • Will take care of my health – daily morning walks (atleast 20min brisk), I guess I have to consider being an early riser πŸ™‚
    • Have felt I am more productive when I use Pomodoro technique (25mins – then 5mins break) – will use that more often. (writing this blog on a Pomodoro :P) – helps well with procrastination!
    • Plan well my tasks and schedule!
    • For Stress and Anxiety – try Box Breathing, (inhale: 4s, hold: 4s, exhale: 4s, hold: 4s), listen to some music πŸ™‚
    • HAVE FUN!
  • Behavioural Patterns

    Memento Pattern

    • Undo in text editor

    Observer Pattern

    • WeatherStation broadcasting temperature to DisplayDevice

    Strategy Pattern

    • PaymentService processing Payments with PaymentStrategy

    Command Pattern

    • Bold, Italic Command Buttons – Generic button

    Template Pattern

    • DataParser – JSONParser, CSVParser

    Iterator Pattern

    • Java Iterable – .hasNext(), .next()

    State Pattern

    • TransportationService – ETA/Directions based on TransportationMode

    Mediator Pattern

    • ChatUser sending messages to other ChatUsers in a ChatRoom

  • UML Relationships

    Association

    Are related but can exist independently.
    Eg: Professor teaches Students.

    Aggregation

    Weak ‘has-a’ relationship.
    Eg: Department has Professors, but Professors exists independently.

    Composition

    Strong ‘has-a’ relationship.
    Eg: House has Rooms, Rooms can’t exist independently.

    Inheritance

    ‘is-a’ relationship.
    Eg: Dog is Animal.

    Dependency

    A class depends on another for its functionality.
    Eg: Printer depends on Document.

    Realization

    A class implementing an interface.

  • Year 2025!

    Well, this year I am planning big again haha – heads down and execute.
    Want to read a lot, get a new job!
    Excited for this year πŸ™‚

  • 2D Arrays

    Multi-dimensional Arrays

    • 1D: Marks of Students in a subject
    • 2D: Marks of Students in multiple subjects
    • 3D: Image – Rows x Columns in B/W image (2D) but in colour images we have 3D arrays will R, G, B values.
    • 4D: Videos – Images with time
    • ND

    Input/ Output

    #include <iostream>
    using namespace std;
    
    void print(int arr[][100], int n, int m) // pass by ref, passing arr size of row is optional
    {
    
      for (int i = 0; i < n; i++)
      {
        for (int j = 0; j < m; j++)
        {
          cout << arr[i][j] << '\t';
        }
        cout << endl;
      }
    }
    
    int main()
    {
      int arr[100][100];
    
      int n, m; // n: rows / m: cols
      cin >> n >> m;
    
      for (int i = 0; i < n; i++)
      {
        for (int j = 0; j < m; j++)
        {
          cin >> arr[i][j];
        }
      }
    
      print(arr, n, m);
    }
    • In Memory: Row Major (mostly used), Column Major

    2D Character Arrays

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
      char nums[][10] = {"one", "two", "three", "eighteen", "seventy", "hundred"};
    
      cout << nums[3] << endl; // nums[3] returns address but cout prints as string unlike int
      cout << nums[3][2] << endl;
    
      for (int i = 0; i < 6; i++)
      {
        cout << nums[i] << " ";
      }
      cout << endl;
    
      return 0;
    }
  • Character Arrays: Strings

    • End of the string is marked by NULL character ‘\0’ – so cout can print the string and not start printing garbage values
    • cin can take in only first word and will not take words after the whitespace
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    int main()
    {
      char a[10];
      char b[] = {'a', 'b', 'c', 'd'};       // wrong - gets garbage value too
      char c[] = {'a', 'b', 'c', 'd', '\0'}; // correct
      char d[10] = "abc";
    
      char e[100];
      // cout << c << endl;
    
      cin >> e; // issue is you can't input strings like "hello world"
      cout << e << endl;
    
      cout << "c: "
     << "strlen: " << strlen(c) << " sizeof: " << sizeof(c) << endl; // sizeof gives +1 because of NULL char
    
      return 0;
    }

    cin.get()

    • accepts all characters but does so – one at a time from the input buffer
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
      char sentence[100];
    
      char temp = cin.get(); // takes one character at a time from the input buffer
      int len = 0;
      // while (temp != '#') // takes input until # is encountered
    
      while (temp != '\n') // ALSO, add a check len < 100 ! or seg fault
      {
        // cout << temp;
        sentence[len++] = temp;
        // len++;
        temp = cin.get();
      }
      sentence[len] = '\0';
    
      cout << sentence << endl;
      cout << "Length: " << len << endl;
    
      return 0;
    }

    Count Digits, Spaces, Letters

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
      char ch = cin.get();
    
      // counts
      int alphabets = 0;
      int spaces = 0;
      int digits = 0;
    
      while (ch != '\n')
      {
        if (ch >= '0' && ch <= '9') // '0' - '9' has ascii values
        {
          digits++;
        }
        else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
        {
          alphabets++;
        }
        else if (ch == ' ' || ch == '\t')
        {
          spaces++;
        }
        ch = cin.get();
      }
      cout << "Alphabets: " << alphabets << " Spaces: " << spaces << " Digits: " << digits << endl;
      return 0;
    }

    cin.getline()

    #include <iostream>
    using namespace std;
    
    int main()
    {
      // char sentence[1000];
      // cin.getline(sentence, 1000); // by default stops at '\n'
    
      char paragraph[1000];
      cin.getline(paragraph, 1000, '#'); // at '#'
    
      cout << paragraph << endl;
      return 0;
    }

    Shortest Path

    #include <iostream>
    using namespace std;
    
    int main()
    {
      char route[1000];
      cin.getline(route, 1000);
    
      int x = 0, y = 0;
    
      for (int i = 0; route[i] != '\0'; i++)
      {
        switch (route[i])
        {
        case 'N':
          y++;
          break;
        case 'S':
          y--;
          break;
        case 'E':
          x++;
          break;
        case 'W':
          x--;
          break;
        }
      }
    
      cout << "x: " << x << " y: " << y << endl;
      // I
      if (x >= 0 and y >= 0)
      {
        while (y--)
        {
          cout << "N";
        }
        while (x--)
        {
          cout << "E";
        }
      }
      // II
      else if (x >= 0 && y < 0)
      {
        while (y++)
        {
          cout << "S";
        }
        while (x--)
        {
          cout << "E";
        }
      }
      // III
      else if (x <= 0 && y <= 0)
      {
        while (y++)
        {
          cout << "S";
        }
        while (x++)
        {
          cout << "W";
        }
      }
      // IV
      else if (x <= 0 && y >= 0)
      {
        while (y--)
        {
          cout << "N";
        }
        while (x++)
        {
          cout << "W";
        }
      }
    
      cout << endl;
      return 0;
    }

    Copy, Concat, Compare

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main()
    {
    
      char a[100] = "apple";
      char b[100];
    
      cout << strlen(a) << endl;
    
      strcpy(b, a); // copy a to b
      cout << b << endl;
    
      cout << strcmp(a, b) << endl; // returns 0 if same
    
      char web[] = "www.";
      char domain[] = "aritra.xyz";
    
      cout << strcat(web, domain) << endl; // concatenates two strings
    
      cout << strcmp(web, a) << endl; // returns a +ve or -ve value on false
    
      return 0;
    }

    Largest String

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    int main()
    {
    
      char sentence[1000];
      char largest[1000];
    
      int n;
      int largest_len = 0;
      cout << "Enter no. of lines: ";
      cin >> n;
      cin.get(); // to consume \n
    
      while (n--)
      {
        cin.getline(sentence, 1000);
        int len = strlen(sentence);
        if (len > largest_len)
        {
          strcpy(largest, sentence);
          largest_len = len;
        }
      }
    
      cout << largest_len << " - " << largest << endl;
      return 0;
    }

    String class & getline()

    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
      string s; // dynamic vector
      string s1 = "hello world";
      string s2("hello world");
    
      // cout << s1 << endl;
      // cout << s2 << endl;
    
      getline(cin, s);
      // getline(cin, s, '#');
      for (char ch : s)
      {
        cout << ch << ", ";
      }
      cout << endl;
      //
      int n;
      cin >> n;
      cin.get();
      string temp;
      vector<string> sarr;
      while (n--)
      {
        getline(cin, temp);
        sarr.push_back(temp);
      }
      for (string s : sarr)
      {
        cout << s << ", ";
      }
      cout << endl;
      return 0;
    }

    Run Length Encoding

    #include <iostream>
    using namespace std;
    
    string compressString(string s)
    {
      int n = s.length();
      string res;
      for (int i = 0; i < n; i++)
      {
        int count = 1;
        while (i < n - 1 && s[i] == s[i + 1])
        {
          count++;
          i++;
        }
        res += s[i];
        res += to_string(count);
      }
    
      if (res.length() >= s.length())
      {
        return s;
      }
      return res;
    }
    
    int main()
    {
      cout << compressString("aaaabbbbccccccccc") << endl;
      cout << compressString("abcd") << endl;
    
      return 0;
    }
  • Sorting

    Bubble Sort

    We take the largest element to the end by repeated swapping.

    #include <iostream>
    using namespace std;
    
    void bubble_sort(int arr[], int n)
    {
    
      for (int i = 0; i < n - 1; i++) // or 1 to n-1
      {
        for (int j = 0; j < n - i - 1; j++)
        {
    
          if (arr[j] > arr[j + 1])
          {
            swap(arr[j], arr[j + 1]);
          }
        }
      }
    }
    
    int main()
    {
      int arr[] = {-2, 3, 4, -1, 5, -12, 6, 1, 3};
      int n = sizeof(arr) / sizeof(int);
    
      bubble_sort(arr, n);
    
      for (int x : arr)
      {
        cout << x << " ";
      }
      cout << endl;
    }

    Insertion Sort

    • Like cards – say you have cards numbered 1, 3, 4 and you get a card numbered 2 – so you make space for 2 by moving 4, then 3 – then you insert the card numbered 2.
    #include <iostream>
    using namespace std;
    
    void insertion_sort(int arr[], int n)
    {
      for (int i = 1; i < n; i++)
      {
        int current = arr[i];
        int prev = i - 1;
    
        while (prev >= 0 && current < arr[prev])
        {
          arr[prev + 1] = arr[prev];
          prev--;
        }
    
        arr[prev + 1] = current;
      }
    }
    
    int main()
    {
      int arr[] = {-2, 3, 4, -1, 5, -12, 6, 1, 3};
      int n = sizeof(arr) / sizeof(int);
    
      insertion_sort(arr, n);
    
      for (int x : arr)
      {
        cout << x << " ";
      }
      cout << endl;
    
      return 0;
    }
    

    Selection Sort

    • Find the minimum element in the unsorted part and swap it with the beginning element of the unsorted array.
    #include <bits/stdc++.h>
    using namespace std;
    
    void selection_sort(int arr[], int n)
    {
      for (int pos = 0; pos < n - 1; pos++) // 0 to n - 2, coz last element will become the largest
      {
        int min_pos = pos;
        for (int curr = pos; curr < n; curr++)
        {
    
          if (arr[curr] < arr[min_pos])
          {
            min_pos = curr;
          }
        }
        swap(arr[pos], arr[min_pos]);
      }
    }
    
    int main()
    {
      int arr[] = {-2, 3, 4, -1, 5, -12, 6, 1, 3};
      int n = sizeof(arr) / sizeof(int);
    
      selection_sort(arr, n);
    
      for (int x : arr)
      {
        cout << x << " ";
      }
      cout << endl;
    
      return 0;
    }
    

    Inbuilt Sort and Comparators

    • O(n * logn)
    #include <iostream>
    #include <algorithm> // contains sort()
    using namespace std;
    
    // comparator
    bool compare(int a, int b)
    {
      return a > b;
    }
    
    int main()
    {
      int arr[] = {-2, 3, 4, -1, 5, -12, 6, 1, 3};
      int n = sizeof(arr) / sizeof(int);
    
      // sort(arr, arr + n, greater<int>()); // greater - inbuilt comparator
      // reverse(arr, arr + n);
    
      sort(arr, arr + n, compare); // compare func is passed
    
      //
      for (int x : arr)
      {
        cout << x << " ";
      }
      cout << endl;
    
      return 0;
    }
    

    Couting Sort

    • O(N + Range)
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void counting_sort(int arr[], int n)
    {
      // find largest element to find the range (size of freq/ count arr)
      int largest = -1;
      for (int i = 0; i < n; i++)
      {
        largest = max(largest, arr[i]);
      }
    
      // create count/ freq arr
      vector<int> freq(largest + 1, 0);
      for (int i = 0; i < n; i++)
      {
        freq[arr[i]]++;
      }
    
      // put back elements in order
      int j = 0;
      for (int i = 0; i <= largest; i++) // O(n + range)
      {
        while (freq[i] > 0)
        {
          arr[j] = i;
          j++;
          freq[i]--;
        }
      }
    }
    
    int main()
    {
    
      int arr[] = {88, 97, 10, 12, 15, 1, 5, 6, 12, 5, 8};
      int n = sizeof(arr) / sizeof(int);
    
      counting_sort(arr, n);
    
      for (int x : arr)
      {
        cout << x << " ";
      }
    
      cout << endl;
    
      return 0;
    }
  • Arrays

    Arrays are Linear Data Structures with elements of same type stored in contiguous memory locations

    Why we even need arrays?

    • To store multiple related elements – say marks of 100 students in a class, it’s hectic to declare 100 different variables – instead we can have a “marks” array with the size of 100 to store the marks.
    • Arrays can be accessed with indexes. marks[0] gives the mark of the first student
    • Indexes in arrays start with 0 and ends with n-1 (where n = size of array)
    • Arrays store elements of same datatype – an array can’t have both int and string (For example: {10, “orange”} but this is possible: {“10”, “orange”} as both “10” and “orange” are strings)
    • strings are character arrays – NULL character marks the end of the char array.
    • Static Allocation – size of an array can’t be changed once declared, compiler determines the size of the array.

    Input/Output – Update Arrays

    • Sometimes, you may want to use array from 1 to n instead of 0 to n-1 (but for that you need to declare the size to n + 1)

    Passing Arrays to Functions

    • You need to pass array’s size when passing it to a function because array’s are passed by reference.
    You have to pass the size in the function
    • Pass the size from main()
    • If the array is changed inside the function – the main array will be changed as the function references the same array in memory.

    Linear Search

    • O(n) – time complexity
    • Traverses through each element one by one to find the key.
    key = 5

    Binary Search

    • Works with Sorted Arrays
    • O(log n) time complexity

    Reversing an array

    • one way is iterating the array in reverse, copy the elements to a new array *extra space :(*, then copy the elements from new array to the main array
    • a better way is having two pointers (start & end) and keep on swapping the elements. (code below and diagram below!)

    Print Pairs

    Print Subarrays

    • elements should be contiguous
    • 3 for loops: k for looping through i to j

    Largest Subarray Sum

    Brute Force

    • O(n ^ 3)

    Prefix Sum

    • prefix array takes extra space
    • O(n ^ 2) time

    Kadane’s Algorithm

    • O(n)

    Vectors

    • Dynamic array
    • Vectors on getting full creates a new vector with double the size and copies the elements from old vector to the new one.
  • Hello World!

    I have been planning to start writing a blog to document my learnings and life. I wanted to start writing to clear my thoughts. So, here it is.

    Well, Why WordPress.com then? Answering that, I have tried using other blogging platforms like Hugo, Jekyll. You can host them for free on Netlify or GitHub Pages, I know. But, I always had a hard time working with them, they are really good and maybe I again start using them but for now I am thinking of using WordPress.com as it has been here for a while, it was what first got me started into exploring Web Development and I feel it is not going away anytime soon too. I don’t want to self-host a WordPress blog now as:

    1. I don’t have the money to pay for a server. 😦
    2. I don’t want to manage my site because I won’t have the time.
    3. I want to focus more on writing. I want to practice writing here first, if I ever switch back to Hugo and figure it out πŸ™‚
    4. I don’t want to lose my work in the future just because I couldn’t pay the server bill, and my stuff stays there.