## programming challenge – LeetCode: C # binary tree level order traversal

Please check the performance. and also naming convention

https://leetcode.com/problems/binary-tree-level-order-traversal/

Given a binary tree, flip the level order through its nodes & # 39;
values. (i.e. from left to right, level by level).

For example:

``````Given binary tree (3,9,20,null,null,15,7),
3
/
9  20
/
15   7

return its level order traversal as:
(
(3),
(9,20),
(15,7)
)
``````
``````using System.Collections.Generic;
using System.Linq;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
///
/// https://leetcode.com/problems/binary-tree-level-order-traversal/
///
(TestClass)
public class BinaryTreeLevelOrderTraversalTest
{

//      3
//     /
//    9  20
//   /
//  15   7
(TestMethod)
public void TreeTest()
{
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.left.left = new TreeNode(15);
root.left.right = new TreeNode(7);
IList> res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root);
CollectionAssert.AreEqual(res(0).ToList(), new List{3});
CollectionAssert.AreEqual(res(1).ToList(), new List{9,20});
CollectionAssert.AreEqual(res(2).ToList(), new List{15,7});
}

(TestMethod)
public void OneNodeTreeTest()
{
TreeNode root = new TreeNode(3);
IList> res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root);
CollectionAssert.AreEqual(res(0).ToList(), new List { 3 });
}
}

public class BinaryTreeLevelOrderTraversalClass
{
public static IList> LevelOrder(TreeNode root)
{
List> res = new List>();
if (root == null)
{
return res;
}
Queue Q = new Queue();

Q.Enqueue(root);

int counter = 0; // which level
while (Q.Count > 0)
{
int children = Q.Count;
for (int i = 0; i < children; i++)
{
var temp = Q.Dequeue();
if (temp.left != null)
{
Q.Enqueue(temp.left);
}
if (temp.right != null)
{
Q.Enqueue(temp.right);
}
}
counter++;
}
return res;
}
}

}
``````

## algorithms – (Leetcode) Combinatorial sum – How to generate a set of solutions from a number of sets of solutions?

The following question is taken from Leetcode titled & # 39; Combination Sum & # 39;

Given a set of candidate (candidate) numbers (no duplicates) and a target (target) number, look for all unique combinations in candidates where the number of candidates matches the target.

The same repeated number can be chosen from the candidates an unlimited number of times.

Note:

1. All numbers (including the target) will be positive integers.
2. The solution set must not contain duplicate combinations.

Example 1:

Entry: candidates = (2,3,6,7), target = 7,
A set of solutions is:
(
(seven),
(2,2,3)
)

Example 2:

Entry: candidates = (2,3,5), target = 8,
A set of solutions is:
(
(2,2,2,2),
(2,3,3)
(3,5)
)

To solve this problem, I applied dynamic programming, in particular the 2D bottom-up tabulation approach. The method is quite similar to the problem of the backpack 0/1, that is to say if we want to use an element in the candidates or not.

Here is my code:

``````class Solution:
def combinationSum(self, candidates: List(int), target: int) -> List(List(int)):
if not len(candidates):
return 0
dp = ( (1) + (0)*target for _ in range(len(candidates) + 1))
for row in range(1, len(candidates) + 1):
for col in range(1, target+1):
dp(row)(col) += dp(row - 1)(col)
if col - candidates(row-1) >= 0:
dp(row)(col) += dp(row)(col - candidates(row-1))
print(dp(-1)(-1))
``````

However, my codes above do not provide a solution. Instead, it gives the number of elements in the set of solutions.

I tried to generate a set of solutions from my codes above, but to no avail. Can anyone help me?

## Is there an absolute guide to improving the Leetcode problem?

I am new in leetcode grinding and I hang whenever I try to solve a new problem.

## Unit Testing – How Do Sites Like LeetCode & HackerRank Test the Accuracy of Your Code?

You do not know if this question is here, but I've always wondered how sites like Leetcode and HackerRank are testing your code. Let's say you code in Java for a question like,

Find all duplicates in a table

After clicking the Submit button, the code is sent as part of a POST request to the primary server, then what is the most likely action.

As a student always, I guess if the code is compiled successfully, it is then tested on a Java-specific test suite (I present a bunch of JUnit lol tests). Perhaps it's a separate microservice that manages tests and tracks metrics (such as memory usage, number of past test cases, etc.). ?

If so, this means that each Leetcode question has several test suites, each testing the same test cases but just being written in different languages ​​(for example, JUnit tests for Java, unittest for Python, etc.). . I did not think about it much, but I have the feeling that could job. However, would this be the right way to solve this type of software engineering problem?

## programming challenge – LeetCode: Daily Temperatures C #

https://leetcode.com/problems/daily-temperatures/

Give a list of daily temperatures T, return a list such as, for
every day in the entry, tells you the number of days waiting
until a warmer temperature. If there is no future day for which this

For example, given the temperature list T = (73, 74, 75, 71, 69,
72, 76, 73), your output must be (1, 1, 4, 2, 1, 1, 0, 0).

Note: The temperature length will be in the range (1, 30000). Each
the temperature will be an integer in the interval (30, 100).

``````using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
///
/// https://leetcode.com/problems/daily-temperatures/
///
(TestClass)
public class DailyTemperaturesTest
{
(TestMethod)
public void ExmapleTest()
{
int() temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
int() days = {1, 1, 4, 2, 1, 1, 0, 0};
CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures));
}

(TestMethod)
public void SmallExampleTest()
{
int() temperatures = {73, 72, 73, 74};
int() days = {3, 1, 1, 0};
CollectionAssert.AreEqual(days, DailyTemperaturesClass.DailyTemperatures(temperatures));
}
}

public class DailyTemperaturesClass
{
public static int() DailyTemperatures(int() T)
{
int() days = new int(T.Length);
// we are using a stack to remeber all the temps we saw until now,
// the next time we see one which is higher we pop all the temps which are lower
Stack stack = new Stack();
for (int i = T.Length - 1; i >= 0; i--)
{
//if the current temp is greater or equals to the top of the stack
// pop all until found one which is higher temp then T(i)
while (stack.Count > 0 && T(i) >= T(stack.Peek()))
{
stack.Pop();
}

if (stack.Count == 0)
{
days(i) = 0;
}
else
{
days(i) = stack.Peek() - i; // number of days between higher temp to i
}
stack.Push(i);// we push current temp to the Top of the stack.
}

return days;
}
}
}
``````

## programming challenge – LeetCode: Burst Balloons C #

https://leetcode.com/problems/burst-balloons/

N balls given, indexed from 0 to n-1. Each balloon is painted with
a number on it represented by an array nums. You are invited to burst
the balls. If you explode the ball, you will get numbers (left) *
nums (i) * nums (right) parts. Here on the left and on the right are adjacent indexes
of i. After the burst, the left and the right become adjacent.

Find the most coins you can collect by popping the balloons
wisely.

Note:

You can imagine nums (-1) = nums (n) = 1. They are not real
you can not burst them. 0 ≤ n ≤ 500, 0 ≤ num (i) ≤ 100

``````Example:

Input: (3,1,5,8)
Output: 167
Explanation: nums = (3,1,5,8) --> (3,5,8) -->   (3,8)   -->  (8)  --> ()
coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167
``````
``````using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

{
///
/// https://leetcode.com/problems/burst-balloons/
///
(TestClass)
public class BurstBalloonsTest
{
(TestMethod)
public void TestExample()
{
int() nums = {3, 1, 5, 8};
BurstBalloonsClass burst = new BurstBalloonsClass();
Assert.AreEqual(167, burst.MaxCoins(nums));
}
}

public class BurstBalloonsClass
{

public int MaxCoins(int() nums)
{
int() numbers = new int(nums.Length +2);  // we add 2 because of the question
// nums(-1) = nums(n) = 1
int n = 1;
foreach (var x in nums)
{
if (x > 0) // we care only about positive values for profit
{
numbers(n++) = x;
}
}
numbers(0) = numbers(n++) = 1;
int()() memo = new int(n)();
for (var index = 0; index < memo.Length; index++)
{
memo(index)= new int(n);
}
// we allocate NxN matrix for memoization

return Burst(memo, numbers, 0, n - 1);
}

private int Burst(int()() memo, int() numbers, int left, int right)
{
if (left + 1 == right)
{
return 0;
}

if (memo(left)(right) > 0)
{
return memo(left)(right);
}

int ans = 0;
// we try all the options between left and right
// we compare the answers of all of the options and the maxmial one
// if poped all of the ballons from left to u and from i to right we have only an option to pop
// numbers(left) * numbers(i) * numbers(right)
for (int i = left + 1; i < right; ++i)
{
ans = Math.Max(ans, numbers(left) * numbers(i) * numbers(right)
+ Burst(memo, numbers, left, i)
+ Burst(memo, numbers, i, right));
}

memo(left)(right) = ans;
return ans;
}
}
}
``````

## performance – LeetCode: Reconstruction of the queue by C # height

https://leetcode.com/problems/queue-reconstruction-by-height/

Suppose you have a random list of people in a queue. Each
nobody is described by a pair of integers $$(h, k)$$, or $$h$$ is the
height of the person and $$k$$ is the number of people in front of this
who has a height greater than or equal to $$h$$. Write a
algorithm to rebuild the queue.

Note: The number of people is less than 1,100.

``````Example

Input:
((7,0), (4,4), (7,1), (5,0), (6,1), (5,2))

Output:
((5,0), (7,0), (5,2), (6,1), (4,4), (7,1))
``````

``````using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace SortingQuestions
{
///
/// https://leetcode.com/problems/queue-reconstruction-by-height/
///
(TestClass)
public class ReconstructQueueTest
{
(TestMethod)
public void ReconstructQueueExampleTest()
{
int()() people = new int(6)();
people(0) = new() { 7, 0 };
people(1) = new() { 4, 4 };
people(2) = new() { 7, 1 };
people(3) = new() { 5, 0 };
people(4) = new() { 6, 1 };
people(5) = new() { 5, 2 };

int()() expected = new int(6)();
expected(0) = new() { 5, 0 };
expected(1) = new() { 7, 0 };
expected(2) = new() { 5, 2 };
expected(3) = new() { 6, 1 };
expected(4) = new() { 4, 4 };
expected(5) = new() { 7, 1 };
int()() res = ReconstructQueueClass.ReconstructQueue(people);
for (var index = 0; index < res.Length; index++)
{
CollectionAssert.AreEqual(expected(index), res(index));
}
}
}

public class ReconstructQueueClass
{
public static int()() ReconstructQueue(int()() people)
{
int()() res = new int(people.Length)();
Array.Sort(people, new PairComparer());

List list = new List();

for (int i = 0; i < people.Length; i++)
{
list.Add(i); //a list of indices 0,1,2,3,4...
res(i) = new int(2);
}

for (int i = 0; i < people.Length; i++)
{
int index = list(people(i)(1)); //the index in the result is the number of people before you
res(index)(0) = people(i)(0);
res(index)(1) = people(i)(1);
list.RemoveAt(people(i)(1)); // we remove the index from the list so we keep only the un used ones
}
return res;
}
}

///
/// sort the people, have min height first
/// for the same height for example 5,0 and 5,2
/// 5,2 is before 5,0
///
public class PairComparer : IComparer
{
public int Compare(int() x, int() y)
{
if (x(0) != y(0))
{
return x(0) - y(0);// we want min value first
}
return y(1) - x(1);
}
}
}
``````

## programming challenge – LeetCode: Top K frequent items C #

https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799

Given an array of non-empty integers, return the most frequent k
elements.

Example 1

Entry: nums = (1,1,1,2,2,3), k = 2

Output: (1,2)

Example 2

Entry: nums = (1), k = 1
Release: (1) Note:

You can assume that k is still valid, 1 ≤ k ≤ number of unique elements.
The time complexity of your algorithm must be better than O (n log n), where
n is the size of the array.

``````using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

//good example for bucket sort
namespace SortingQuestions
{
///
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
///
(TestClass)
public class TopKFrequentTest
{
(TestMethod)
public void SimpleUseCaseTest()
{
int() nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int() expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}

public class TopKFrequentClass
{
public static IList TopKFrequent(int() nums, int k)
{
Dictionary number2Count = new Dictionary();

//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count(num) = temp + 1;
}

List() bucket = new List(nums.Length + 1);

//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
//    0 times -> none
//    1 times -> number 3
//    2 times -> number 2
//    3 times -> number 1
//    4 times -> none
//    5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count(key);
if (bucket(frequency) == null)
{
bucket(frequency) = new List();
}
}

List result = new List();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket(pos) != null)
{
}
}

return result;
}
}
}
``````

I like this question a lot and it's sometimes hard to understand how to sort through a bucket here.

I know that I can also use MaxHeap.
Since C # does not have MaxHeap, do you think that using a SortedList can help here in one way or another with performance. remember the limits of the question

Thank you please consider for the performance

## Algorithm Leetcode Power Set in Python

my implementation:

``````import copy
def subsets(nums: List(int)) -> List(List(int)):
"""
deduce reccurence relation of power set as such:
current power set = prev powerset U (prev_powerset U new element)
"""
#bottom up approach

power_set = (())
for i in range(len(nums)):
element = nums(i)
new_power_set = copy.deepcopy(power_set)
for key in range(len(new_power_set)):
new_power_set(key).append(element)
# unionized the two sets
power_set+=new_power_set
return power_set
``````

recursive implementation of leetcode:

``````   def subsets(nums: List(int)) -> List(List(int)):

def directed_pow_set(to_be_selected,selected_so_far):
if to_be_selected == len(nums):
power_set.append(selected_so_far)
return
directed_pow_set(to_be_selected+1,selected_so_far)
directed_pow_set(to_be_selected+1, selected_so_far + (nums(to_be_selected)))
power_set = ()
directed_pow_set(0,())
return power_set
``````

I am very confused as to how one would get the intuition for the recursive approach, compared to my iterative implementation, which can be made even more intuitive by proving that the total number of sub- sets of a defined size is $$2 ^ n$$ with induction. I have drawn the recursive tree for recursive implementation for an example of input,$$n = (1,2,3)$$ but that did not really help me understand. TLDR: I just have trouble understanding why the DFS version works and how would you find the intuition to solve this type of problems?

## python – Leetcode the longest substring without duplicates

``````class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest = ''
max_len = 0
for key,value in enumerate(s):
if value in longest:
longest = longest(longest.index(value)+1:) + value
else:
longest+=value
max_len = max(max_len,len(longest))
return max_len

``````

Here is my solution for the leetcode's "longest-sub-string-without-characters-repetitive" question. I do not quite understand why the complexity of my time is so effective (99% of all Python submissions). Since the strings are immutable in python, assuming a force of length n, will not my algorithm be $$1 + 2 + 3 + … n-1 + n = 0 (n ^ 2)$$ time? But the optimal solution is on $$O (n)$$ however, the time of testing indicates that my solution is as good as the optimal one provided. Am I missing something? Moreover, I have trouble proving the complexity of the space for my solution.