이 블로그 검색

2023년 8월 3일 목요일

What is LCA(Lowest Common Ancestor)

Definition

Lowest Common Ancestor, LCA.

LCA is an algorithm or concept used in tree structures to find the closest common ancestor of two nodes.

Example


In the above binary tree, the LCA of 4 and 6 is 1.

LCA(4, 6) = 1

Purpose

The purpose of the LCA is to efficiently find the closest common ancestor of two nodes in a tree structure.

Cases to consider using LCA

You should consider using the LCA algorithm in the following cases:

  • When you need to calculate the distance between two nodes in a tree structure.
  • When you need to find nodes belonging to a subtree rooted at a specific node.
  • When calculating the shortest path in computer networks.
  • When solving collision detection and other problems in game development.

Cases not suitable for using LCA

The LCA algorithm is limited to tree structures and cannot be used in other data structures. Additionally, if the problem doesn't involve finding the common ancestor of two nodes, there is no need to use LCA.

Advantages

  • It can efficiently find the LCA of two nodes with a reasonable time complexity.
  • After preprocessing, query operations can be performed quickly.

Disadvantages

  • The LCA algorithm is restricted to tree structures and cannot be applied to other data structures.

Implementation Steps

  1. Compute the parent and depth information for each node in the binary tree.
  2. This step is called preprocessing.
  3. Move towards the parents of the two nodes for which you want to find the LCA.
  4. While moving towards the parents, check for the first intersection of the nodes.
  5. The first intersection is the LCA.

Example

import java.util.ArrayList;
import java.util.List;

class Node {
    int value;
    Node parent;
    List<Node> children;

    Node(int value) {
        this.value = value;
        this.children = new ArrayList<>();
    }
}

public class LCAExample {

    private static void preprocess(Node node, Node parent, int depth) {
        node.parent = parent;

        for (Node child : node.children) {
            preprocess(child, node, depth + 1);
        }
    }

    private static Node findLCA(Node node1, Node node2) {
        int depth1 = getDepth(node1);
        int depth2 = getDepth(node2);

        while (depth1 > depth2) {
            node1 = node1.parent;
            depth1--;
        }

        while (depth2 > depth1) {
            node2 = node2.parent;
            depth2--;
        }

        while (node1 != node2) {
            node1 = node1.parent;
            node2 = node2.parent;
        }

        return node1;
    }

    private static int getDepth(Node node) {
        int depth = 0;
        while (node.parent != null) {
            node = node.parent;
            depth++;
        }
        return depth;
    }

    public static void main(String[] args) {
        Node root = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        Node node7 = new Node(7);

        root.children.add(node2);
        root.children.add(node3);
        node2.children.add(node4);
        node2.children.add(node5);
        node3.children.add(node6);
        node3.children.add(node7);

        preprocess(root, null, 0);

        Node lcaNode = findLCA(node4, node5);
        System.out.println("LCA: " + lcaNode.value); // 2

        lcaNode = findLCA(node4, node6);
        System.out.println("LCA: " + lcaNode.value); // 1

        lcaNode = findLCA(node3, node7);
        System.out.println("LCA: " + lcaNode.value); // 3
    }
}

What is Python Variables

what is Variable

symbol represent some number or String that may change.

data types

scalar and non-scalar both object

scalar

  • int : integer
  • float : real number
  • bool : True or False
  • none : Null

non-scalar

  • String : data values that are made up of ordered sequences of characters, such as "hello world"

How to check data type

print(type(Variable))

addtional infomation

Case-Sensitive

a and A are different variable

Casting

x = str(4)    # "4"
y = int(4)    # 4
z = float(4) # 4.0

2023년 7월 30일 일요일

LeetCode 1512. Number of Good Pairs Java Solution

Problem

Number of Good Pairs - LeetCode

Problem Solving Approach

This is a problem that tests your ability to work with nested loops (for loop inside another for loop) and multiple conditions (if statements with the && operator).

Github Link

https://github.com/eunhanlee/LeetCode_1512_NumberofGoodPairs_Solution.git

Time Complexity: O(n^2), Space Complexity: O(k)

class Solution {
    /**
     * Calculates the number of identical pairs in the given array.
     *
     * @param nums An array of integers.
     * @return The number of identical pairs in the array.
     */
    public int numIdenticalPairs(int[] nums) {
        int counter = 0; // A variable to count the number of identical pairs.

        // Iterate through each element of the array.
        for (int i = 0; i < nums.length; i++) {
            // Compare the current element with the rest of the elements in the array.
            for (int j = 0; j < nums.length; j++) {
                // Check if the element at index j is equal to the element at index i
                // and ensure that j is greater than i to avoid duplicates.
                if (nums[j] == nums[i] && j > i) {
                    counter++; // Increment the counter if a good pair is found.
                }
            }
        }

        return counter; // Return the total number of identical pairs in the array.
    }
}

LeetCode 2235. Add Two Integers Java Solution

Problem

Add Two Integers - LeetCode

Problem Solving Approach

  • This problem tests the ability to perform simple arithmetic operations and return the result.
  • The parentheses () are not necessary to use, considering Java operator precedence.

Reference

Java Operator Precedence

Github Link

https://github.com/eunhanlee/LeetCode_2235_AddTwoIntegers_Solution.git

Time Complexity: O(1), Space Complexity: O(1)

class Solution {
    /**
     * Returns the sum of two integers.
     *
     * @param num1 The first integer.
     * @param num2 The second integer.
     * @return The sum of num1 and num2.
     */
    public int sum(int num1, int num2) {
        return num1 + num2;
    }
}

LeetCode 1431. Kids With the Greatest Number of Candies Java Solution

Problem

Kids With the Greatest Number of Candies - LeetCode

Approach

  • Algorithm
    • First, find the maximum value in the given array.
    • Traverse each element in the array, and for each kid, check if adding the extra candies makes their candy count greater than or equal to the maximum count.
    • If it is greater, add true to the result list, otherwise add false.
  • There is no need to put candy + extraCandies inside parentheses in the if statement (if(candy + extraCandies < max)). Java operator precedence will handle it correctly without the need for explicit grouping.
  • The if statement can be replaced with the ternary operator:
result.add(candy + extraCandies >= max ? true : false);

References

Java Operator Precedence

What is Java Ternary Operator(?:)

Github Link

https://github.com/eunhanlee/LeetCode_1431_KidsWiththeGreatestNumberofCandies_Solution.git

Time Complexity: O(n), Space Complexity: O(n)

/**
 * Determines whether each kid can have the maximum number of candies considering the extra candies.
 *
 * @param candies       An integer array representing the number of candies each kid has.
 * @param extraCandies  The number of extra candies each kid can have.
 * @return              A list of booleans representing whether each kid can have the maximum number of candies.
 */
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
    // Find the maximum number of candies in the given array.
    int max = 0;
    for (int candy : candies) {
        max = Math.max(max, candy);
    }

    // Check if each kid can have the maximum number of candies.
    List<Boolean> result = new ArrayList<>(candies.length);
    for (int candy : candies) {
        // If adding the extra candies makes the current kid's candy count greater than or equal to the maximum count,
        // consider them able to have the maximum number of candies.
        result.add(candy + extraCandies >= max ? true : false);
    }

    return result;
}

LeetCode 217. Contains Duplicate Java Solution

Problem

Problem Link

Time Complexity: O(n), Space Complexity: O(n)

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // Create a HashMap to store the elements of the array.
        HashMap<Integer, Integer> map = new HashMap<>();

        // Traverse all elements in the array.
        for (int temp : nums) {
            // Check if the current element exists in the HashMap.
            if (map.containsKey(temp)) {
                // If it exists, it means there is a duplicate element in the array, so return true.
                return true;
            } else {
                // If it doesn't exist, add the current element to the HashMap.
                // The value '1' is used to indicate the existence of a duplicate element.
                map.put(temp, 1);
            }
        }
        // If there are no duplicate elements, return false.
        return false;
    }
}

Explanation

  • HashSet internally uses HashMap. Therefore, you can achieve the same result using HashSet.

What is Java Ternary Operator(?:)

Definition

The question mark operator (? :) is a conditional operator that selects one of two expressions based on the evaluation result of a condition. It can achieve results similar to an if statement.

Structure

if (Condition) { result = expression1; } else { result = expression2; }

result = Condition ? expression1 : expression2;

It is equivalent to an if statement.


Considerations for Use

When using the ternary operator, the following considerations should be taken into account:

Advantages

  • Code Conciseness: It allows expressing logic where a value is chosen based on a condition in a single line, enhancing code readability and conciseness.
  • Expression Reusability: The selected expression can be assigned to a variable or used as part of other expressions, thus increasing reusability.

Disadvantages

  • Readability of Complex Conditions: While the ternary operator is suitable for simple conditions, it may reduce readability for complex condition expressions. In such cases, using if-else statements might be more appropriate.

Step-by-Step Usage

  1. Write the condition expression. The condition expression should evaluate to a boolean value (true or false).
  2. Follow the condition expression with a question mark (?).
  3. Write the expression to be selected if the condition is true, followed by a colon (:).
  4. Write the expression to be selected if the condition is false.
  5. The result of the ternary operator is the value of the selected expression.

Example

int age = 18;
String message = (age >= 18) ? "You are an adult." : "You are a minor.";

System.out.println(message); // Output: "You are an adult."

In the example above, the value of the age variable is 18 or older, so the condition (age >= 18) evaluates to true. Therefore, the expression1, "You are an adult.", is selected and assigned to the message variable.

Logic Gate Truth Tables & Definitions

Logic Gate Truth Tables Java Code !A // NOT A&B // AND ~(A&B) // NAND A|B // OR ~(A|B) // XOR A^B // XOR ~(A^B) // XNOR ~A // Inve...