LeetCode TIL 241205

두선아 DusunaΒ·2024λ…„ 12μ›” 4일

algorithm

λͺ©λ‘ 보기
1/14

Try to solve problems in JavaScript, Python, and Java.
This is TIL(memo of key learnings) for solving problems in these languages,
but mostly python.


Solved Problems πŸ“

241205:
1. validate-binary-search-tree
2. contains-duplicate
3. valid-palindrome
4. top-k-frequent-elements


Key Learnings πŸ€”

Why is an empty node a valid BST?

validate-binary-search-tree

An empty node (null node) in a Binary Search Tree (BST) is valid BST.

Because a BST's definition states that for any node, all values in the left subtree must be smaller, and all values in the right subtree must be larger.

An empty node doesn't violate this condition, as there are no values to compare.

if rootNode is None:
    return True # empty node is valid BST

When should I use self in Python?

validate-binary-search-tree:

In Python, self is used in instance methods of a class to refer to the current instance of the class.

It uses to access the instance's attributes and methods!

It's required as the first parameter in instance methods and is how the class instance is referenced within those methods.

If you declare a method in a class, you need to use self as the first parameter.

Should I use Long for declaring infinity in Java?

validate-binary-search-tree:
github link

In Java, you can use Long, Double, Float, and Integer for declaring infinity.

  • Long.MAX_VALUE
  • Double.POSITIVE_INFINITY
  • Float.POSITIVE_INFINITY
  • Integer.MAX_VALUE
TypeConstantRange/Precision
LongLong.MAX_VALUE64-bit signed integer, max: 9223372036854775807
DoubleDouble.POSITIVE_INFINITY64-bit floating point, positive/negative infinity
FloatFloat.POSITIVE_INFINITY32-bit floating point, positive/negative infinity
IntegerInteger.MAX_VALUE32-bit signed integer, max: 2147483647

πŸ‘‰ Choose the appropriate type depends on your specific use case.

What if I pass a long value to a function expecting a float ?

validate-binary-search-tree: github link

There was a test case that failed because of precision loss when passing a long value to a function expecting a float.

When you pass a long value to a function expecting a float, precision loss can occur.

public boolean checkBST(TreeNode node, float min, float max) {...} // I passed a long value to this function!

This happens because floating-point numbers have limited precision, especially when representing large integers, leading to potential inaccuracies in the comparison.

And passing a long value makes the comparison inaccurate.

πŸ‘‰ So, if there was a test case that handling a long value keep failing?
Do check if you passed a expected type to the function.

Review Comment πŸ’­

πŸ’¬ How can I compare a value with " " in Python? (ps. it's not is)

valid-palindrome: Github Comment Link

In Python, is checks for object identity, not equality.

To compare a string with an empty space (" "), you should use the equality operator (==) rather than is.

if s == " ": # 🟒 use this.
if s is " ": # πŸ”΄ don't use this.

πŸ’¬ Avoid using regex in Python (for avoiding regex overhead)

valid-palindrome: Github Comment Link
isalnum(): https://www.w3schools.com/python/ref_string_isalnum.asp

Code A: Using regex

  • possibly slower than using isalnum() because of regex overhead.
# Code A
def isPalindrome(self, s: str) -> bool:
    if s == " ":
        return True

    reg = "[^a-z0-9]"
    converted_s = re.sub(reg, "", s.lower())

    return converted_s == converted_s[::-1]

Code B: Using isalnum()

  • using python's built-in isalnum() method.
  • using python generator expression.
def isPalindrome(self, s: str) -> bool:
    if s == " ":
        return True

    s = s.lower() 
    converted_s = ''.join(c for c in s if c.isalnum()) 
    # Convert the string to lowercase and keep only alphanumeric characters
    # .isalnum(): check if the character is alphanumeric.
    
    return converted_s == converted_s[::-1]
profile
μ•ˆλ…•ν•˜μ„Έμš”.

1개의 λŒ“κΈ€

comment-user-thumbnail
2025λ…„ 2μ›” 25일

Great insights! It's intriguing how BST empty nodes and Java data type accuracy are related. Knowing when and how to utilize self in Python and the accuracy loss when passing data types helps write more robust programs. Your clarifications are much appreciated! Geometry Dash

λ‹΅κΈ€ 달기