[Easy] 1304. Find N Unique Integers Sum up to Zero

Given an integer n, return any array containing nunique integers such that they add up to 0.

Example

1 2 3

Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Solution

We have to consider the even and odd situations. if it is odd, set the middle element as 0 and spread left (–) and right (++), if it is even, set the pairs, such as (-1,1), (-2, 2)...

//time:O(n) space: publicvoidpushLeft(Stack<TreeNode> stack, TreeNode root){ if (root == null) return; stack.push(root); pushLeft(stack, root.left); } public List<Integer> getAllElements(TreeNode root1, TreeNode root2){ List<Integer> res = new ArrayList<>(); Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); pushLeft(s1, root1); pushLeft(s2, root2); while (!s1.isEmpty() || !s2.isEmpty()) { Stack<TreeNode> s = null; if (!s1.isEmpty() && !s2.isEmpty()) { s = s1.peek().val > s2.peek().val ? s2 : s1; } elseif (s1.isEmpty()) { s = s2; } elseif (s2.isEmpty()) { s = s1; } TreeNode current = s.pop(); res.add(current.val); pushLeft(s, current.right); } return res; }

[Medium] 1306. Jump Game III

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.

Notice that you can not jump outside of the array at any time.

Example

1 2 3 4 5 6 7 8 9 10 11 12

Input: arr = [4,2,3,0,3,1,2], start = 5 Output: true Explanation: All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3

Input: arr = [4,2,3,0,3,1,2], start = 0 Output: true Explanation: One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3

Solution

We use backtracking strategy to solve this problem and try to iterate all the possibilities. During the process, we also have to keep tracking what element has already visited and prevent TLE.

Code

DFS

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

// time:O(n) space:O(n) publicbooleancanReach(int[] arr, int start){ int n = arr.length; if (arr == null || arr.length == 0) returnfalse; boolean[] visited = newboolean[n]; return dfs(arr, start, visited); }

publicbooleandfs(int[] arr, int start, boolean[] visited){ if (start >= arr.length || start < 0) returnfalse; if (arr[start] == 0) returntrue; if (visited[start]) returnfalse; visited[start] = true; return dfs(arr, start + arr[start], visited) || dfs(arr, start - arr[start], visited); }