Week 1 of My DSA Journey

Khushi SinghKhushi Singh
7 min read

A Beginner’s Guide to Problem-Solving & Java Basic

📖 What I Covered This Week?

This week, I focused on building a strong foundation in programming. Here’s a breakdown of my learning:

1️⃣ Basics of Programming

  • Input & Output in Java & Python

  • Data Types (int, float, char, string, boolean)

  • Conditionals (if-else)

  • Loops (for, while)

2️⃣ Functions

  • Pass by Value vs. Pass by Reference

  • Parameter Passing & Return Types

3️⃣ Time Complexity Fundamentals

  • Big-O Notation and how to analyze the efficiency of a program

  • Common time complexities: O(1), O(log N), O(N), O(N²)

4️⃣ Pattern Problems
I practiced 22 different pattern problems, covering:
✅ Triangle Patterns
✅ Pyramid Patterns
✅ Diamond & Hollow Patterns

5️⃣ Basic Maths problems
I solved problems that helped me think logically and optimize solutions:
✅ Counting Digits in a Number
✅ Reversing a Number
✅ Palindrome Check (121 → True, 123 → False)

Basic of Programming

Input & Output in Java

Java: Scanner class for input, System.out.println() for output

Data Types

Primitive (Java): int, float, char, boolean

1. Printing Output in Java

The System.out.println() method is used to display output:

javaCopyEditSystem.out.println("Hello Java");

2. Variables & Data Types

Variables store values in memory. Java has primitive and non-primitive data types.

Primitive Data Types (Fixed Size)

  • int → Stores whole numbers (int a = 10;)

  • long → For larger integers (long l = 1283903748L;)

  • float → Stores decimal numbers (float pi = 3.14F;)

  • char → Stores single characters (char ch = 'e';)

  • boolean → Stores true or false (boolean isChild = false;)

Non-Primitive Data Types (Variable Size)

  • String → A sequence of characters (String str = "Hello";)

  • Strings have built-in functions, e.g., str.length() returns the length of the string.

3. Taking Input in Java

The Scanner class allows user input. First, create a Scanner object:

javaCopyEditScanner sc = new Scanner(System.in);

Now, you can read input:

  • Integer Input:

      javaCopyEditint age = sc.nextInt();
    
  • Single Word Input (next() captures only the first word):

      javaCopyEditString name = sc.next();
    
  • Full Line Input (nextLine() captures the entire sentence):

      javaCopyEditString fullName = sc.nextLine();
    

4. Comments in Java

  • Single-line comments: // This is a comment

  • Multi-line comments:

      javaCopyEdit/* This is 
         a multi-line comment */
    

Conditionals

Conditional statements allow a program to make decisions based on conditions. Java provides several types of conditional statements:

This Java program takes two integer inputs (n and m) from the user and compares them using conditional statements. If both numbers are equal, it prints "Both are equal". If n is smaller than m, it prints "m is greater than n", otherwise, it prints "n is greater than m". The program demonstrates the use of if-else statements for decision-making based on numerical comparisons.

Output

Loops

Loops help in executing a block of code multiple times until a condition is met. Java provides three types of loops:

1️⃣ For Loop – Used when the number of iterations is known.
2️⃣ While Loop – Used when the number of iterations is not fixed, and it runs as long as a condition is true.

This Java program demonstrates for and while loops for printing numbers. The user inputs a number n. First, the for loop prints numbers from 1 to n. Then, the while loop prints numbers in reverse from n to 1, decrementing n each time.

Functions

Functions (or methods) help break code into reusable blocks, improving readability and efficiency. In Java, functions are defined using the returnType functionName(parameters) {} syntax.

This Java program demonstrates functions and Java’s pass-by-value behavior. It defines themethod(), which prints a message, and swap(int a, int b), which swaps two numbers using a temporary variable. However, since Java is strictly pass-by-value, the changes inside swap() do not affect the original values in main(). The program highlights that Java does not allow returning multiple values directly, and alternatives like arrays or objects must be used. 🚀.

Time Complexity Fundamentals

Big-O Notation is a mathematical concept used to describe the efficiency of an algorithm in terms of time and space as input size increases. It helps compare different algorithms based on their worst-case, average-case, or best-case performance. The notation ignores constant factors and lower-order terms, focusing only on the dominant term that grows the fastest as input size increases.

Common time complexities include O(1) (constant time, e.g., accessing an array index), O(log N) (logarithmic time, e.g., binary search), O(N) (linear time, e.g., iterating through an array), and O(N²) (quadratic time, e.g., nested loops). Understanding these complexities helps in selecting the most efficient algorithm for a given problem. 🚀

Pattern Problems

So there were around 13 problems in the Striver’s sheet for solving pattern problems.Here I will be only sharing the top most necessary problems in DSA perspective.

General Approach

  • We always use nested loops for printing the patterns.The outer loop is mostly responsible for rows whereas the inner loop is concerned with the columns.

  • Somehow connect the inner loop variable with the outer loop variable to print the pattern

Star pattern

Code

Approach: Outer Loop (for i=0 to n-1) → Controls the number of rows.

  • First Inner Loop (for j=0 to n-i-1) → Prints leading spaces to center-align the pyramid.

  • Second Inner Loop (for j=0 to 2*i+1) → Prints * in an increasing odd pattern (1, 3, 5, ...).

  • Third Inner Loop (for j=0 to n-i-1) → Prints trailing spaces (not necessary but maintains symmetry).

Star diamond pattern

Code

Approach: Outer Loop (for i=0 to n-1) → Controls the number of rows.

  • First Inner Loop (for j=0 to n-i-1) → Prints leading spaces to center-align the pyramid.

  • Second Inner Loop (for j=0 to 2*i+1) → Prints * in an increasing odd pattern (1, 3, 5, ...).

  • Third Inner Loop (for j=0 to n-i-1) → Prints trailing spaces (not necessary but maintains symmetry).

  • Now reverse the pattern by adjusting the variables.

Number crown pattern

code

Approach: Outer Loop (for i=1 to n) → Controls the number of rows.

  • First Inner Loop (for j=1 to i) → Prints numbers from 1 to i.

  • Print Spaces (" ".repeat(2*(n-i))) → Adds spaces for symmetry. The number of spaces decreases as i increases.

  • Second Inner Loop (while j>=1) → Prints numbers in reverse from i back to 1.

Basic maths problem

Counting Digits in a Number

Problem: Count digits

Code:

Approach: Extract each digit of n using n % 10 This is stored in r(Remainder).

  • Check if the digit is non-zero and divides n evenly (main_num % r == 0).

  • If true, increment the count.

  • Remove the last digit using n = n / 10.

  • Repeat until n becomes 0.

  • Return the final count of divisible digits

class Solution {
    static int evenlyDivides(int n) {
        // code here
        int main_num=n;
        int count=0;
        while(n>0){
            int r=n%10;   //r here represents the remainder.It give the last digit.
            if(r!=0 && main_num%r==0){
                count++;

            }
            n=n/10;
        }
        return count;
    }
}

Reverse a number

Reverse Integer

Code:

Approach: Extract the last digit using x % 10 and build the reversed number rev = rev * 10 + r.

  • Remove the last digit using x = x / 10 and repeat until x becomes 0.

  • Check for 32-bit integer overflow; if exceeded, return 0.

  • If the original number was negative, return -rev; otherwise, return rev

class Solution {
    public int reverse(int x) {
        int main_num=x;
        x=Math.abs(x);
        int rev=0;
        while(x>0){
            int r=x%10;
            rev=rev*10+r;
            x=x/10;
        }
        if(rev<Math.pow(-2,31) || rev>Math.pow(2,31)-1){
            return 0;
        }
        if(main_num<0){
            return -rev;
        }
        return rev;
    }
}

Palindrome Check (121 → True, 123 → False)

Palindrome number

Code:

Approach: Store the original number in main_num to compare later.

  • Reverse the number by extracting digits (x % 10) and appending them to rev.

  • Continue reversing until x becomes 0.

  • Compare rev with main_num; if they are equal, return true (palindrome), otherwise return false.

class Solution {
    public boolean isPalindrome(int x) {
        int main_num=x;
        int rev=0;
        while(x>0){
            int r=x%10;
            rev=rev*10+r;
            x=x/10;
        }
        return (rev==main_num);
    }
}
0
Subscribe to my newsletter

Read articles from Khushi Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Khushi Singh
Khushi Singh