Leetcode problems

 An archive for my Leetcode problems I've solved.

1578. Minimum Time to Make Rope Colorful

Elixir

defmodule Solution do
  @spec min_cost(colors :: String.t, needed_time :: [integer]) :: integer
  def min_cost(colors, needed_time) do
    color_graph = colors |> String.graphemes()

    Enum.zip(color_graph, needed_time)
    |> traverse(0)
  end

  defp traverse([], accumulator), do: accumulator

  defp traverse([{char, time_a} | [{char, time_b} | tail]], accumulator) when time_a > time_b,
    do: traverse([{char, time_a} | tail], accumulator + time_b)

  defp traverse([{char, time_a} | [{char, time_b} | tail]], accumulator) when time_a <= time_b,
    do: traverse([{char, time_b} | tail], accumulator + time_a)

  defp traverse([_ | tail], accumulator), do: traverse(tail, accumulator)
end


125. Valid Palindrome

Elixir

defmodule Solution do
  @spec is_palindrome(s :: String.t) :: boolean
  def is_palindrome(s) do
    regex = ~r/[\!\@\#\%\^\&\*\(\)\_\+\-\=\[\]\{\}\|\;\'\:\"\,\.\/\<\>\?\~\`\s]/

     s1 = s |> String.replace(regex, "") |> String.downcase
     s1 == String.reverse(s1)
  end
end


49. Group Anagrams

Elixir

defmodule Solution do
  @spec group_anagrams(strs :: [String.t]) :: [[String.t]]
  def group_anagrams(strs) do
    do_group(strs, %{})
    |> Enum.flat_map(fn {_, value} -> [value] end)
  end
 
  defp do_group([], accumulator), do: accumulator
  defp do_group([head | tail], accumulator) do
    key =
      String.to_charlist(head)
    |> Enum.sort()

    case Map.fetch(accumulator, key) do
      {:ok, _} ->
        accumulator = Map.update(accumulator, key, head, fn list ->
          [head | list]
        end)

        do_group(tail, accumulator)
      :error ->
        accumulator = Map.put(accumulator, key, [head | []])

        do_group(tail, accumulator)
    end
  end
end



1. Two Sum

Elixir

defmodule Solution do
  @spec two_sum(nums :: [integer], target :: integer) :: [integer]
  def two_sum(nums, target) do
    num_list =
      nums
      |> Enum.with_index()

    result =
      Enum.reduce_while(num_list, %{}, fn {value, index}, accumulator ->
        accumulator
        remainder = target - value

        if Map.get(accumulator, remainder) do
          {:halt, Map.put(accumulator, :answer, [Map.get(accumulator, remainder), index])}
        else
          {:cont, Map.put(accumulator, value, index)}
        end
      end)

    Map.get(result, :answer)
  end
end



242. Valid Anagram

Elixir

defmodule Solution do
  @spec is_anagram(s :: String.t, t :: String.t) :: boolean
  def is_anagram(s, t) do
    ~c(#{s}) |> Enum.sort() == ~c(#{t}) |> Enum.sort()
  end
end



217. Contains Duplicate

Elixir

defmodule Solution do
  @spec contains_duplicate(nums :: [integer]) :: boolean
  def contains_duplicate(nums), do: do_contains_duplicate(Enum.sort(nums))
  defp do_contains_duplicate([l]), do: false
  defp do_contains_duplicate([head | [head | tail]]), do: true
  defp do_contains_duplicate([head | tail]), do: do_contains_duplicate(tail)
end



4. Median of Two Sorted Arrays

C#

public class Solution {
    public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
        var newArr = nums1.Concat(nums2).OrderBy(x => x).ToArray();
       double result;

        if (newArr.Length % 2 == 0)
        {
            int firstMedian = newArr.Length / 2;
            int secondMedian = firstMedian - 1;

            result = (double)(newArr[firstMedian] + newArr[secondMedian]) / 2;
        }
        else
        {
            int median = (int)newArr.Length / 2;
            result = newArr[median];
        }

        return result;
    }
}


3. Longest Substring Without Repeating Characters

C#

public class Solution {
    public int LengthOfLongestSubstring(string test) {
            int head, tail, max;
            head = tail = 0;
            max = 0;
            string str = "";
            while (tail < test.Length)
            {
                if (str.Contains(test[tail]))
                {
                    head = str.IndexOf(test[tail]) + 1;
                    str = str.Remove(0, head);
                }
                str = String.Concat(str, test[tail]);
                if (max < str.Length)
                {
                    max = str.Length;
                }
                tail++;
            }
        return max;
        }
    }


175. Combine Two Tables

SQL

# Write your MySQL query statement below
select FirstName, LastName, City, State
from Person p left join Address a
on p.PersonId = a.PersonId


2. Add Two Numbers

C#

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {        
        return Calculate(l1, l2);
    }
        public static ListNode Calculate(ListNode list1, ListNode list2)
        {
            int remainder = 0;
            int value = 0;
            value = list1.val + list2.val;
            if (value > 9)
            {
                remainder = (value - value % 10) / 10;
                value %= 10;
            }
            ListNode head = new ListNode(value);
            list1 = list1.next;
            list2 = list2.next;
            ListNode curr = head;
            while (list1 != null || list2 != null)
            {
                if (list1 is null)
                {
                    list1 = new ListNode(0);
                    value = list2.val + remainder;
                }
                else if (list2 is null)
                {
                    list2 = new ListNode(0);
                    value = list1.val + remainder;
                }
                else
                {
                    value = list1.val + list2.val + remainder;
                   
                }
                remainder = 0;
                if (value > 9)
                {
                    remainder = (value - value % 10) / 10;
                    value %= 10;
                }

                ListNode newNode = new ListNode(value);
                curr.next = newNode;
                curr = curr.next;
                list1 = list1.next;
                list2 = list2.next;
            }
            if (remainder > 0)
            {
                curr.next = new ListNode(remainder);
            }
            return head;
        }
}

Comments

Popular posts from this blog

Simulating, configuring and uploading to S3 locally using LocalStack and Elixir

Asus Zenbook 14 OLED 2022 (UX3402) - 3 months later