result, int forOpen, int opened, String prefix) {
18 | if (forOpen == 0) {
19 | result.add(prefix + ")".repeat(Math.max(0, opened)));
20 | return;
21 | }
22 |
23 | if (forOpen > 0) {
24 | generateParenthesis(result, forOpen - 1, opened + 1, prefix + "(");
25 | }
26 |
27 | if (opened > 0) {
28 | generateParenthesis(result, forOpen, opened - 1, prefix + ")");
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/greedy/medium/JumpGame.java:
--------------------------------------------------------------------------------
1 | package solution.greedy.medium;
2 |
3 | /**
4 | * @see Task 55
5 | */
6 | public class JumpGame {
7 |
8 | public boolean canJump(int[] nums) {
9 | int[] arr = new int[nums.length];
10 | int maxStep = 0;
11 | for (int i = 0; i < nums.length; i++) {
12 | if (i > maxStep) return false;
13 | if (i == 0 || arr[i] != 0) {
14 | maxStep = Math.max(maxStep, nums[i] + i);
15 | if (nums[i] + i >= nums.length - 1) return true;
16 |
17 | for (int j = 1; j <= nums[i]; j++) arr[i + j] += 1;
18 | }
19 | }
20 | return false;
21 | }
22 |
23 | public boolean canJump_2(int[] nums) {
24 | int reach = 0;
25 | for (int i = 0; i <= reach; i++) {
26 | reach = Math.max(reach, i + nums[i]);
27 | if (reach >= nums.length - 1) return true;
28 | }
29 | return false;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/binary_search/medium/SearchInRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | package solution.binary_search.medium;
2 |
3 | /**
4 | * @see Task 33
5 | */
6 | public class SearchInRotatedSortedArray {
7 |
8 | public int search(int[] nums, int target) {
9 | int l = 0;
10 | int r = nums.length - 1;
11 | while (l < r) {
12 | int mid = (l + r) / 2;
13 | if (nums[mid] == target) return mid;
14 |
15 | if (nums[l] <= nums[mid]) { // left sorted part
16 | if (target >= nums[l] && target < nums[mid]) {
17 | r = mid - 1;
18 | } else {
19 | l = mid + 1;
20 | }
21 | } else { // right sorted part
22 | if (target > nums[mid] && target <= nums[r]) {
23 | l = mid + 1;
24 | } else {
25 | r = mid - 1;
26 | }
27 | }
28 | }
29 | return nums[l] == target ? l : -1;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/tree/medium/LowestCommonAncestorOfABinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package solution.tree.medium;
2 |
3 | import solution.tree.TreeNode;
4 |
5 | /**
6 | * @see Task 235
7 | *
8 | * TODO Check again later
9 | */
10 | public class LowestCommonAncestorOfABinarySearchTree {
11 |
12 | /**
13 | * LCA Wiki
14 | *
15 | * The lowest common ancestor is defined between two nodes p and q as the lowest node in T
16 | * that has both p and q as descendants (where we allow a node to be a descendant of itself).
17 | */
18 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
19 | if (p.val > root.val && q.val > root.val) {
20 | return lowestCommonAncestor(root.right, p, q);
21 | } else if (p.val < root.val && q.val < root.val) {
22 | return lowestCommonAncestor(root.left, p, q);
23 | } else {
24 | return root;
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Leonid Zemenkov
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/tools.md:
--------------------------------------------------------------------------------
1 | # Tools
2 |
3 | ## Git
4 |
5 | `Git` is a must-learn tool that you will use every day, so you need to know what it is and also know the basic commands.
6 |
7 | `Git` is a version control system that allows you to keep track of changes that occur in a project. `Git` provides a
8 | secure and seamless way for multiple developers to work on the same project.
9 |
10 | 1. [Documentation](https://git-scm.com/book/en/v2)
11 | 2. [Step-by-step Git introduction guide](https://gitimmersion.com/index.html)
12 | 3. [CodeAcademy course](https://www.codecademy.com/learn/learn-git)
13 | 4. [Git cheat sheet](https://education.github.com/git-cheat-sheet-education.pdf)
14 |
15 | ## Docker
16 |
17 | `Docker` allows developers to package applications and their dependencies in an isolated container. This simplifies the
18 | deployment process and ensures that the application will run consistently on any system where `Docker` is installed.
19 |
20 | 1. [Step-by-step guide with labs](https://github.com/docker/labs)
21 | 2. [En Youtube full course](https://youtu.be/3c-iBn73dDE?si=ZR7JiGzdK1nSX9w5)
22 | 3. [Ru Youtube full course](https://youtu.be/n9uCgUzfeRQ?si=QllvUoDlAZ7aNXjm)
23 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/medium/LinkedListCycle2.java:
--------------------------------------------------------------------------------
1 | package solution.two_pointers.medium;
2 |
3 | /**
4 | * @see solution.linked_list.easy.LinkedListCycle
5 | * @see Task 142
6 | */
7 | public class LinkedListCycle2 {
8 |
9 | public ListNode detectCycle(ListNode head) {
10 | if (head == null) return null;
11 | ListNode slow = head;
12 | ListNode fast = head;
13 |
14 | while (fast.next != null && fast.next.next != null) {
15 | fast = fast.next.next;
16 | slow = slow.next;
17 |
18 | if (fast == slow) {
19 | ListNode slow2 = head;
20 | while (slow2 != slow) {
21 | slow = slow.next;
22 | slow2 = slow2.next;
23 | }
24 | return slow;
25 | }
26 | }
27 | return null;
28 | }
29 |
30 | private static class ListNode {
31 | int val;
32 | ListNode next;
33 |
34 | ListNode(int x) {
35 | val = x;
36 | next = null;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/arrays/easy/RemoveDuplicatesFromSortedArray.java:
--------------------------------------------------------------------------------
1 | package solution.arrays.easy;
2 |
3 | /**
4 | * @see Task 26
5 | */
6 | public class RemoveDuplicatesFromSortedArray {
7 |
8 | /**
9 | * Space - O(1)
10 | * Time - O(n)
11 | */
12 | public int removeDuplicates(int[] nums) {
13 | int tmp = 0;
14 | for (int i = 1; i < nums.length; i++) {
15 | if (nums[i] != nums[tmp]) {
16 | tmp++;
17 | nums[tmp] = nums[i];
18 | }
19 | }
20 | return ++tmp;
21 | }
22 |
23 | /**
24 | * Space - O(1)
25 | * Time - O(n)
26 | */
27 | public static int removeDuplicates_2(int[] nums) {
28 | if (nums.length == 0) return 0;
29 |
30 | int slow = 0;
31 | int fast = 1;
32 |
33 | while (fast < nums.length) {
34 | if (nums[fast] != nums[slow]) {
35 | slow++;
36 | nums[slow] = nums[fast];
37 | }
38 | fast++;
39 | }
40 | return slow + 1;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/binary_search/easy/BinarySearch.java:
--------------------------------------------------------------------------------
1 | package solution.binary_search.easy;
2 |
3 | /**
4 | * @see Task 704
5 | */
6 | public class BinarySearch {
7 |
8 | /**
9 | * Recursion
10 | */
11 | public int search(int[] nums, int target) {
12 | return binarySearch(nums, target, 0, nums.length - 1);
13 | }
14 |
15 | private int binarySearch(int[] nums, int t, int l, int r) {
16 | if (l > r) return -1;
17 | if (l == r) return nums[l] == t ? l : -1;
18 | int m = l + (r - l) / 2;
19 | if (nums[m] == t) return m;
20 | if (nums[m] > t) return binarySearch(nums, t, l, m - 1);
21 | return binarySearch(nums, t, m + 1, r);
22 | }
23 |
24 | public int search_2(int[] nums, int target) {
25 | int l = 0;
26 | int r = nums.length - 1;
27 |
28 | while (l <= r) {
29 | int mid = (l + r) / 2;
30 |
31 | if (nums[mid] == target) return mid;
32 | else if (nums[mid] < target) l = mid + 1;
33 | else r = mid - 1;
34 | }
35 |
36 | return -1;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/heap/medium/KClosestPointsToOrigin.java:
--------------------------------------------------------------------------------
1 | package solution.heap.medium;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Comparator;
5 | import java.util.List;
6 | import java.util.PriorityQueue;
7 |
8 | /**
9 | * @see Task 973
10 | */
11 | public class KClosestPointsToOrigin {
12 |
13 | public int[][] kClosest(int[][] points, int k) {
14 | PriorityQueue> queue = new PriorityQueue<>(
15 | Comparator.comparing(l -> Math.sqrt(Math.pow(l.get(0), 2) + Math.pow(l.get(1), 2)))
16 | );
17 |
18 | for (int[] coordinates : points) {
19 | List list = new ArrayList<>();
20 | list.add(coordinates[0]);
21 | list.add(coordinates[1]);
22 | queue.add(list);
23 | }
24 |
25 | int[][] r = new int[k][2];
26 | for (int i = 0; i < k; i++) {
27 | List l = queue.poll();
28 | r[i] = new int[2];
29 | r[i][0] = l.get(0);
30 | r[i][1] = l.get(1);
31 | }
32 | return r;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/easy/ValidPalindrome.java:
--------------------------------------------------------------------------------
1 | package solution.two_pointers.easy;
2 |
3 | /**
4 | * @see Task 125
5 | */
6 | public class ValidPalindrome {
7 |
8 | public boolean isPalindrome_1(String s) {
9 | char[] chars = s
10 | .toLowerCase()
11 | .trim()
12 | .replaceAll("[^a-zA-Z0-9]", "")
13 | .toCharArray();
14 |
15 | for (int left = 0, right = chars.length - 1; left < right; left++, right--) {
16 | if (chars[left] != chars[right]) return false;
17 | }
18 | return true;
19 | }
20 |
21 | public boolean isPalindrome_2(String s) {
22 | int i = 0;
23 | int j = s.length() - 1;
24 | while (i < j) {
25 | while (!Character.isLetterOrDigit(s.charAt(i)) && i < j) i++;
26 | while (!Character.isLetterOrDigit(s.charAt(j)) && j > i) j--;
27 |
28 | if (i > j || Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
29 |
30 | i++;
31 | j--;
32 | }
33 | return true;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/medium/Sum3.java:
--------------------------------------------------------------------------------
1 | package solution.two_pointers.medium;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @see Task 15
7 | */
8 | public class Sum3 {
9 |
10 | public List> threeSum(int[] nums) {
11 | Arrays.sort(nums);
12 | Set> set = new HashSet<>();
13 |
14 | for (int i = 0; i < nums.length - 2; i++) {
15 | int l = i + 1;
16 | int r = nums.length - 1;
17 | while (l < r) {
18 | int sum = nums[i] + nums[l] + nums[r];
19 | if (sum == 0) {
20 | set.add(Arrays.asList(nums[i], nums[l], nums[r]));
21 | l++;
22 | r--;
23 | while (l < r && nums[l - 1] == nums[l]) l++;
24 | while (l < r && nums[r + 1] == nums[r]) r--;
25 | } else if (sum > 0) {
26 | r--;
27 | while (l < r && nums[r + 1] == nums[r]) r--;
28 | } else {
29 | l++;
30 | while (l < r && nums[l - 1] == nums[l]) l++;
31 | }
32 | }
33 | }
34 | return new ArrayList<>(set);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/stack/medium/EvaluateReversePolishNotation.java:
--------------------------------------------------------------------------------
1 | package solution.stack.medium;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * @see Task 150
7 | */
8 | public class EvaluateReversePolishNotation {
9 | public int evalRPN(String[] tokens) {
10 | Stack stack = new Stack<>();
11 | for (String s : tokens) {
12 | switch (s) {
13 | case "+":
14 | stack.push(stack.pop() + stack.pop());
15 | break;
16 | case "-":
17 | int r = stack.pop();
18 | int l = stack.pop();
19 | stack.push(l - r);
20 | break;
21 | case "*":
22 | stack.push(stack.pop() * stack.pop());
23 | break;
24 | case "/":
25 | int right = stack.pop();
26 | int left = stack.pop();
27 | stack.push(left / right);
28 | break;
29 | default:
30 | stack.push(Integer.parseInt(s));
31 | break;
32 | }
33 | }
34 | return stack.pop();
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/stack/medium/MinStack.java:
--------------------------------------------------------------------------------
1 | package solution.stack.medium;
2 |
3 |
4 | /**
5 | * @see Task 155
6 | */
7 | public class MinStack {
8 |
9 | Node defaultNode = new Node();
10 | Node head;
11 |
12 | public MinStack() {
13 | head = defaultNode;
14 | }
15 |
16 | public void push(int val) {
17 | if (head == defaultNode) {
18 | head = new Node(val, defaultNode, val);
19 | } else {
20 | head = new Node(val, head, Math.min(val, head.min));
21 | }
22 | }
23 |
24 | public void pop() {
25 | if (head != defaultNode) {
26 | head = head.prev;
27 | }
28 | }
29 |
30 | public int top() {
31 | if (head == defaultNode) return 0;
32 | return head.val;
33 | }
34 |
35 | public int getMin() {
36 | if (head == defaultNode) return 0;
37 | return head.min;
38 | }
39 |
40 | private static class Node {
41 | int val;
42 | Node prev;
43 | int min;
44 |
45 | public Node() {
46 | }
47 |
48 | public Node(int val, Node prev, int min) {
49 | this.val = val;
50 | this.prev = prev;
51 | this.min = min;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/arrays/easy/TwoSum.java:
--------------------------------------------------------------------------------
1 | package solution.arrays.easy;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * @see Task 1
8 | */
9 | public class TwoSum {
10 |
11 | /**
12 | * Space - O(n)
13 | * Time - O(n)
14 | */
15 | public int[] twoSum(int[] nums, int target) {
16 | Map map = new HashMap<>();
17 |
18 | for (int i = 0; i < nums.length; i++) {
19 | int diff = target - nums[i];
20 | if (map.containsKey(diff)) {
21 | return new int[]{map.get(diff), i};
22 | }
23 | map.put(nums[i], i);
24 | }
25 | return new int[]{};
26 | }
27 |
28 | /**
29 | * Space - O(1)
30 | * Time - O(n)
31 | */
32 | public static int[] findPairWithSum(int[] nums, int target) {
33 | int left = 0;
34 | int right = nums.length - 1;
35 |
36 | while (left < right) {
37 | int sum = nums[left] + nums[right];
38 | if (sum == target) {
39 | return new int[]{nums[left], nums[right]};
40 | } else if (sum < target) {
41 | left++;
42 | } else {
43 | right--;
44 | }
45 | }
46 | return new int[]{};
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/tree/medium/BinaryTreeRightSideView.java:
--------------------------------------------------------------------------------
1 | package solution.tree.medium;
2 |
3 | import solution.tree.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 | import java.util.Queue;
9 |
10 | /**
11 | * @see Task 199
12 | */
13 | public class BinaryTreeRightSideView {
14 |
15 | /**
16 | * Основная идея:
17 | * сохранить размер текущей очереди (size), пройти через первые size элементов и сохранить всех детей в очередь.
18 | * При этом, при добавлении элементов в очередь, сначала добавляем правого ребенка.
19 | * Это позволяет гарантировать, что первым элементом во вложенном цикле будет самый правый элемент уровня.
20 | */
21 | public List rightSideView(TreeNode root) {
22 | List result = new ArrayList<>();
23 | if (root == null) return result;
24 | Queue q = new LinkedList<>();
25 | q.add(root);
26 | while (!q.isEmpty()) {
27 | int size = q.size();
28 | for (int i = 0; i < size; i++) {
29 | TreeNode node = q.poll();
30 | if (i == 0) result.add(node.val);
31 | if (node.right != null) q.add(node.right);
32 | if (node.left != null) q.add(node.left);
33 | }
34 | }
35 | return result;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/easy/IntersectionOfTwoLinkedLists.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.easy;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | /**
9 | * @see Task 160
10 | */
11 | // TODO check again interesting approach with swap tmp in the end
12 | public class IntersectionOfTwoLinkedLists {
13 |
14 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
15 | if (headA == null || headB == null) return null;
16 | ListNode tmpA = headA;
17 | ListNode tmpB = headB;
18 |
19 | while (tmpA != tmpB) {
20 | tmpA = tmpA == null ? headB : tmpA.next;
21 | tmpB = tmpB == null ? headA : tmpB.next;
22 | }
23 | return tmpA;
24 | }
25 |
26 | /**
27 | * With extra space
28 | */
29 | public ListNode getIntersectionNode_2(ListNode headA, ListNode headB) {
30 | if (headA == null || headB == null) return null;
31 |
32 | Set set = new HashSet<>();
33 | ListNode tmp = headA;
34 | while (tmp != null) {
35 | set.add(tmp);
36 | tmp = tmp.next;
37 | }
38 | tmp = headB;
39 | while (tmp != null) {
40 | if (set.contains(tmp)) return tmp;
41 | tmp = tmp.next;
42 | }
43 | return null;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/medium/ReorderList.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.medium;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | /**
6 | * @see Task 143
7 | */
8 | public class ReorderList {
9 | public void reorderList(ListNode head) {
10 | if (head == null || head.next == null) return;
11 |
12 | //Find middle of list with slow and fast pointer
13 | ListNode slow = head;
14 | ListNode fast = head.next;
15 | while (fast != null && fast.next != null) {
16 | slow = slow.next;
17 | fast = fast.next.next;
18 | }
19 |
20 | // Reverse second part of the list
21 | // [1 -> 2 -> 3 -> 4 -> 5 -> 6] -> [1 -> 2 -> 3] and [6 -> 5 -> 4]
22 | ListNode second = slow.next;
23 | slow.next = null;
24 | ListNode prev = null;
25 | while (second != null) {
26 | ListNode tmp = second.next;
27 | second.next = prev;
28 | prev = second;
29 | second = tmp;
30 | }
31 |
32 | // Merge two lists [1 -> 2 -> 3] and [6 -> 5 -> 4]
33 | ListNode first = head;
34 | second = prev;
35 | while (second != null) {
36 | ListNode tmp = first.next;
37 | ListNode tmp2 = second.next;
38 | first.next = second;
39 | second.next = tmp;
40 | first = tmp;
41 | second = tmp2;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/binary_search/medium/SearchA2DMatrix.java:
--------------------------------------------------------------------------------
1 | package solution.binary_search.medium;
2 |
3 | /**
4 | * @see Task 74
5 | */
6 | public class SearchA2DMatrix {
7 |
8 | /**
9 | * 1. Сначала ищем строку [row] в которой может располагаться наш элемент
10 | * 2. Ищем элемент в строке бинарным поиском
11 | */
12 | public boolean searchMatrix(int[][] matrix, int target) {
13 | int rows = matrix.length - 1;
14 | int colums = matrix[0].length - 1;
15 |
16 | int l = 0;
17 | int r = rows;
18 | while (l < r) {
19 | int m = l + (r - l) / 2;
20 | if (matrix[m][0] == target) return true;
21 |
22 | if (matrix[m][0] > target) {
23 | if (m == 0) return false;
24 | r = m - 1;
25 | } else {
26 | if (m == rows || matrix[m + 1][0] > target) {
27 | l = m;
28 | break;
29 | }
30 | l = m + 1;
31 | }
32 | }
33 |
34 | int row = l;
35 | l = 0;
36 | r = colums;
37 | while (l <= r) {
38 | int m = l + (r - l) / 2;
39 | if (matrix[row][m] == target) return true;
40 | if (matrix[row][m] > target) {
41 | r = m - 1;
42 | } else {
43 | l = m + 1;
44 | }
45 | }
46 | return false;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/tree/medium/BinaryTreeLevelOrderTraversal.java:
--------------------------------------------------------------------------------
1 | package solution.tree.medium;
2 |
3 | import solution.tree.TreeNode;
4 |
5 | import java.util.LinkedList;
6 | import java.util.List;
7 | import java.util.Queue;
8 |
9 | /**
10 | * @see Task 102
11 | */
12 | public class BinaryTreeLevelOrderTraversal {
13 |
14 | /**
15 | * Основаная идея:
16 | * запомнить размер текущего уровня дерева (levelSize) и последовательно обработать все узлы этого уровня.
17 | * После этого перейти к следующему уровню и повторить процесс до тех пор, пока очередь не станет пустой.
18 | */
19 | public List> levelOrder(TreeNode root) {
20 | List> list = new LinkedList<>();
21 | if (root == null) return list;
22 |
23 | Queue q = new LinkedList<>();
24 | q.add(root);
25 | int levelSize = q.size();
26 | List level = new LinkedList<>();
27 | while (!q.isEmpty()) {
28 | TreeNode node = q.poll();
29 | level.add(node.val);
30 | if (node.left != null) q.add(node.left);
31 | if (node.right != null) q.add(node.right);
32 |
33 | levelSize--;
34 | if (levelSize == 0) {
35 | list.add(level);
36 | level = new LinkedList<>();
37 | levelSize = q.size();
38 | }
39 | }
40 | return list;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/greedy/medium/ValidParenthesisString.java:
--------------------------------------------------------------------------------
1 | package solution.greedy.medium;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * @see Task 678
7 | */
8 | public class ValidParenthesisString {
9 |
10 | public boolean checkValidString(String s) {
11 | Stack openBracketIndexes = new Stack<>();
12 | Stack starIndexes = new Stack<>();
13 |
14 | for (int i = 0; i < s.length(); ++i) {
15 | switch (s.charAt(i)) {
16 | case '(':
17 | openBracketIndexes.push(i);
18 | break;
19 | case ')':
20 | if (openBracketIndexes.size() > 0) openBracketIndexes.pop(); // if we have brackets
21 | else if (starIndexes.size() > 0) starIndexes.pop(); // if not brackets do we have stars
22 | else return false; // closing bracket without opening and star
23 | break;
24 | default:
25 | starIndexes.push(i);
26 | }
27 | }
28 | // if we left with some opening bracket that over stars con cover up
29 | while (openBracketIndexes.size() > 0 && starIndexes.size() > 0) {
30 | if (openBracketIndexes.peek() > starIndexes.peek()) return false;
31 | openBracketIndexes.pop();
32 | starIndexes.pop();
33 | }
34 |
35 | return openBracketIndexes.size() == 0;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Stub.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.*;
3 |
4 | public class Stub {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | out.close();
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/medium/AddTwoNumbers.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.medium;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | /**
6 | * @see Task 2
7 | */
8 | public class AddTwoNumbers {
9 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
10 | boolean extraOne = false;
11 | boolean l1Smaller = false;
12 |
13 | ListNode t1 = l1;
14 | ListNode p1 = null;
15 | ListNode t2 = l2;
16 | ListNode p2 = null;
17 | while (t1 != null || t2 != null) {
18 | int sum = 0;
19 | if (t1 == null) {
20 | sum = t2.val;
21 | l1Smaller = true;
22 | }
23 | if (t2 == null) sum = t1.val;
24 | if (t1 != null && t2 != null) sum = t1.val + t2.val;
25 | if (extraOne) sum += 1;
26 | extraOne = sum / 10 > 0;
27 | sum = sum % 10;
28 | if (t1 != null) {
29 | t1.val = sum;
30 | p1 = t1;
31 | t1 = t1.next;
32 | }
33 | if (t2 != null) {
34 | t2.val = sum;
35 | p2 = t2;
36 | t2 = t2.next;
37 | }
38 | }
39 | if (extraOne) {
40 | if (l1Smaller) {
41 | p2.next = new ListNode(1);
42 | } else {
43 | p1.next = new ListNode(1);
44 | }
45 | }
46 | return l1Smaller ? l2 : l1;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/medium/CopyListWithRandomPointer.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.medium;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * @see Task 138
8 | */
9 | public class CopyListWithRandomPointer {
10 | public Node copyRandomList(Node head) {
11 | if (head == null) return null;
12 | Map map = new HashMap<>();
13 |
14 | Node origNode = head;
15 | Node newHead = null;
16 | Node copyPrev = null;
17 | while (origNode != null) {
18 | Node copy = map.getOrDefault(origNode, new Node(origNode.val));
19 | map.put(origNode, copy);
20 |
21 | if (newHead == null) newHead = copy;
22 | if (copyPrev != null) copyPrev.next = copy;
23 |
24 | if (origNode.random != null) {
25 | Node randomCopy = map.getOrDefault(origNode.random, new Node(origNode.random.val));
26 | copy.random = randomCopy;
27 | map.put(origNode.random, randomCopy);
28 | }
29 |
30 | copyPrev = copy;
31 | origNode = origNode.next;
32 | }
33 | copyPrev.next = null;
34 | return newHead;
35 | }
36 |
37 | private static class Node {
38 | int val;
39 | Node next;
40 | Node random;
41 |
42 | public Node(int val) {
43 | this.val = val;
44 | this.next = null;
45 | this.random = null;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/interview-questions/src/main/java/spring/TransactionService.java:
--------------------------------------------------------------------------------
1 | package spring;
2 |
3 | import org.springframework.transaction.TransactionStatus;
4 | import org.springframework.transaction.annotation.Propagation;
5 | import org.springframework.transaction.annotation.Transactional;
6 | import org.springframework.transaction.support.TransactionCallbackWithoutResult;
7 | import org.springframework.transaction.support.TransactionTemplate;
8 |
9 | public class TransactionService {
10 | private final TransactionTemplate transactionTemplate;
11 |
12 | public TransactionService(TransactionTemplate transactionTemplate) {
13 | this.transactionTemplate = transactionTemplate;
14 | }
15 |
16 | @Transactional
17 | public void withInternalTransaction() {
18 | int one = 1, two = 2;
19 | internalTransaction();
20 | System.out.println(one + two);
21 | transactionTemplate.execute(new TransactionCallbackWithoutResult() {
22 | @Override
23 | protected void doInTransactionWithoutResult(TransactionStatus status) {
24 | internalTransaction();
25 | }
26 | });
27 | }
28 |
29 | @Transactional(propagation = Propagation.REQUIRES_NEW)
30 | public void internalTransaction() {
31 | System.out.println("Internal transaction call");
32 | }
33 |
34 | @Transactional
35 | public void longTransaction() throws InterruptedException {
36 | System.out.println("Start long work.");
37 | Thread.sleep(10000);
38 | System.out.println("Work is completed.");
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Round_919_Task4.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Round_919_Task4 {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | out.close();
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/sliding_window/medium/LongestSubstringWithoutRepeatingCharacters.java:
--------------------------------------------------------------------------------
1 | package solution.sliding_window.medium;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * @see Task 3
8 | */
9 | public class LongestSubstringWithoutRepeatingCharacters {
10 |
11 | /**
12 | * Основная идея:
13 | * Мы должны итерироваться по строке и добавлять символы во множество (set), если они отсутствуют в нем.
14 | * Если символ уже присутствует во множестве, то мы должны удалить все символы, находящиеся перед этим повторением.
15 | *
16 | * Пример:
17 | * s = "asdfghjd"
18 | * Тогда мы придем к ситуации, когда set -> [a,s,d,f,g,h,j] и символ = d
19 | * Следовательно нам нужно удалить все символы до 'd', те [a,s,d]
20 | * и как результат мы получим сет [f,g,h,j,d] с уникальными элементами
21 | */
22 | public int lengthOfLongestSubstring(String s) {
23 | Set set = new HashSet<>();
24 | int max = 0;
25 | for (int i = 0; i < s.length(); i++) {
26 | char c = s.charAt(i);
27 | if (set.contains(c)) {
28 | // удаляем все до повтора
29 | while (c != s.charAt(i - set.size())) {
30 | set.remove(s.charAt(i - set.size()));
31 | }
32 | } else {
33 | set.add(c);
34 | }
35 | if (set.size() > max) max = set.size();
36 | }
37 | return max;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/easy/MergeTwoSortedLists.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.easy;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | /**
6 | * @see Task 21
7 | */
8 | public class MergeTwoSortedLists {
9 |
10 | public ListNode mergeTwoLists_1(ListNode list1, ListNode list2) {
11 | ListNode head = new ListNode();
12 | ListNode tmp = head;
13 | while (list1 != null || list2 != null) {
14 | if (list1 == null) {
15 | tmp.next = list2;
16 | list2 = null;
17 | continue;
18 | }
19 |
20 | if (list2 == null) {
21 | tmp.next = list1;
22 | list1 = null;
23 | continue;
24 | }
25 |
26 | if (list1.val < list2.val) {
27 | tmp.next = list1;
28 | list1 = list1.next;
29 | } else {
30 | tmp.next = list2;
31 | list2 = list2.next;
32 | }
33 | tmp = tmp.next;
34 | }
35 | return head.next;
36 | }
37 |
38 | /**
39 | * Recursion
40 | */
41 | public ListNode mergeTwoLists_2(ListNode list1, ListNode list2) {
42 | if (list1 == null) return list2;
43 | if (list2 == null) return list1;
44 |
45 | if (list1.val < list2.val) {
46 | list1.next = mergeTwoLists_2(list1.next, list2);
47 | return list1;
48 | } else {
49 | list2.next = mergeTwoLists_2(list2.next, list1);
50 | return list2;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task4A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.*;
3 |
4 | /**
5 | * Task 4A= b) {
60 | h += tmp / b;
61 | tmp = tmp / b + tmp % b;
62 | }
63 | out.println(h);
64 |
65 | out.close();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Preparing for a Java Developer Interview
2 |
3 | This repository contains helpful materials, algorithmic tasks, and Java questions to help you successfully prepare for a
4 | technical interview for a Java developer position.
5 |
6 | ## Content
7 |
8 | 1. [Algorithmic problems](./algorithms)
9 | 2. [Java interview questions](./interview-questions)
10 | 3. [Must have tools](tools.md)
11 |
12 | ## 1. Algorithmic problems
13 |
14 | The [algorithms module](/algorithms) contains solutions for the most popular algorithmic problems that can often be found on
15 | interviews.
16 |
17 | ## 2. Top Java interview questions
18 |
19 | The [interview-questions module](/interview-questions) contains popular Java questions that are often asked in technical interviews.
20 | Each question is accompanied by a detailed answer to help you better understand the topic and prepare for the discussion
21 | on interviews. In this section you will also find additional resources to help you deepen your knowledge of Java.
22 |
23 | ## How to use this repository?
24 |
25 | You can `fork` this repository on your computer to study algorithmic problem solutions locally and learn Java questions.
26 | You can also make your own improvements, add new tasks or questions as you see fit useful to other users.
27 |
28 | We welcome your contributions and suggestions! If you want to make changes or add something new, just create
29 | pull request, and we will review your request to include the changes in the project.
30 |
31 | ## License
32 |
33 | This project is distributed under the [MIT](./LICENSE) license. Please read the license before using this project.
34 |
35 | -------------------------------------------------------------------------------
36 |
37 | We hope this repository will help you successfully prepare for your Java Developer interview. Good luck in your training
38 | and interviewing!
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task479A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task479A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int a = sc.nextInt();
54 | int b = sc.nextInt();
55 | int c = sc.nextInt();
56 |
57 | int max = a+b+c;
58 | max = Math.max(max, a*b*c);
59 | max = Math.max(max, (a+b)*c);
60 | max = Math.max(max, a*(b+c));
61 |
62 | out.println(max);
63 |
64 | out.close();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task58A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task58A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | String s = sc.nextLine();
54 | String hello = "hello";
55 | int i = 0;
56 | for (char c : s.toCharArray()) {
57 | if (c == hello.charAt(i)) i++;
58 | if (i == hello.length()) break;
59 | }
60 | out.println(i == hello.length() ? "YES" : "NO");
61 |
62 | out.close();
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/binary_search/medium/TimeBasedKeyValueStore.java:
--------------------------------------------------------------------------------
1 | package solution.binary_search.medium;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @see Task 981
7 | */
8 | public class TimeBasedKeyValueStore {
9 |
10 | /**
11 | * With binary search
12 | */
13 | public static class TimeMap {
14 |
15 |
16 | Map>> map;
17 |
18 | public TimeMap() {
19 | map = new HashMap<>();
20 | }
21 |
22 | public void set(String key, String value, int timestamp) {
23 | if (!map.containsKey(key)) map.put(key, new ArrayList<>());
24 | map.get(key).add(new Pair<>(value, timestamp));
25 | }
26 |
27 | public String get(String key, int timestamp) {
28 | if (!map.containsKey(key)) return "";
29 | List> list = map.get(key);
30 | return search(list, timestamp);
31 | }
32 |
33 | private String search(List> list, int timestamp) {
34 | int start = 0;
35 | int end = list.size() - 1;
36 | while (start < end) {
37 | int mid = start + (end - start + 1) / 2;
38 | if (list.get(mid).second <= timestamp) {
39 | start = mid;
40 | } else {
41 | end = mid - 1;
42 | }
43 | }
44 | return list.get(start).second <= timestamp
45 | ? list.get(start).first
46 | : "";
47 | }
48 | }
49 |
50 | private static class Pair {
51 | F first;
52 | S second;
53 |
54 | public Pair(F first, S second) {
55 | this.first = first;
56 | this.second = second;
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task500A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task500A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int t = sc.nextInt();
55 |
56 | int tmp = 1;
57 | for (int i = 0; i < n - 1; i++) {
58 | int v = sc.nextInt();
59 | if (tmp - 1 == i) tmp += v;
60 | if (tmp >= t) break;
61 | }
62 |
63 | out.println(tmp == t ? "YES" : "NO");
64 | out.close();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/heap/medium/TaskScheduler.java:
--------------------------------------------------------------------------------
1 | package solution.heap.medium;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @see Task 621
7 | */
8 | // TODO I know that it's not optimum, but it's easy to understand
9 | public class TaskScheduler {
10 |
11 | public int leastInterval(char[] tasks, int n) {
12 | Map map = new HashMap<>();
13 | Queue q = new PriorityQueue<>(Collections.reverseOrder(Comparator.comparing(node -> node.counter)));
14 |
15 | for (char letter : tasks) map.compute(letter, (l, v) -> v == null ? 1 : v + 1);
16 | for (char letter : map.keySet()) q.add(new Node(letter, map.get(letter)));
17 |
18 | Map> waiting = new HashMap<>();
19 | int round = 0;
20 | while (!q.isEmpty() || !waiting.isEmpty()) {
21 | round++;
22 | Node node = q.poll();
23 | if (node != null) {
24 | node.counter--;
25 | if (node.counter > 0) {
26 | if (n > 0) {
27 | List list = waiting.getOrDefault(round + n, new ArrayList<>());
28 | list.add(node);
29 | waiting.put(round + n, list);
30 | } else {
31 | q.add(node);
32 | }
33 | }
34 | }
35 | if (waiting.containsKey(round)) {
36 | q.addAll(waiting.get(round));
37 | waiting.remove(round);
38 | }
39 | }
40 | return round;
41 | }
42 |
43 | private class Node {
44 | char letter;
45 | int counter;
46 |
47 | Node(char letter, int counter) {
48 | this.letter = letter;
49 | this.counter = counter;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task478B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 | import java.util.function.Function;
4 |
5 | public class Task478B {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | long n = sc.nextInt();
55 | long m = sc.nextInt();
56 |
57 | Function f = (k) -> k * (k - 1) / 2;
58 |
59 | long min = (n % m) * f.apply(n / m + 1) + (m - n % m) * f.apply(n / m);
60 | long max = f.apply(n - m + 1);
61 |
62 | out.println(min + " " + max);
63 | out.close();
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/README-ru.md:
--------------------------------------------------------------------------------
1 | # Подготовка к собеседованию на Java разработчика
2 |
3 | Этот репозиторий содержит полезные материалы, алгоритмические задачи и вопросы по Java, которые помогут вам успешно
4 | подготовиться к техническому собеседованию на позицию Java разработчика.
5 |
6 | ## Содержание
7 |
8 | 1. [Алгоритмические задачи](./algorithms)
9 | 2. [Вопросы по Java](./interview-questions)
10 |
11 | ## 1. Алгоритмические задачи
12 |
13 | Модуль "algorithms" содержит решения для самых популярных алгоритмических задачек, которые часто можно встретить на
14 | собеседованиях.
15 |
16 | ## 2. Топовые вопросы по Java
17 |
18 | Модуль "interview-questions" содержит популярные вопросы по Java, которые часто задают на технических собеседованиях.
19 | К каждому вопросу прилагается подробный ответ, который поможет вам лучше понять тему и подготовиться к обсуждению на
20 | собеседовании. В этом разделе вы также найдете дополнительные материалы, которые помогут вам углубить свои знания в
21 | Java.
22 |
23 | ## Как использовать данный репозиторий?
24 |
25 | Вы можете клонировать этот репозиторий на свой компьютер, чтобы локально изучать решения алгоритмических задач и изучать
26 | вопросы по Java. Вы также можете внести свои собственные улучшения, добавить новые задачи или вопросы, если считаете их
27 | полезными для других пользователей.
28 |
29 | Мы приветствуем ваши вклады и предложения! Если вы хотите внести изменения или добавить что-то новое, просто создайте
30 | pull request, и мы рассмотрим вашу заявку на включение изменений в проект.
31 |
32 | ## Лицензия
33 |
34 | Этот проект распространяется под лицензией [MIT](./LICENSE). Пожалуйста, ознакомьтесь с лицензией перед использованием
35 | этого проекта.
36 |
37 | -------------------------------------------------------------------------------
38 |
39 | Мы надеемся, что этот репозиторий поможет вам успешно подготовиться к собеседованию на позицию Java разработчика. Удачи
40 | в вашем обучении и прохождении собеседований!
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/medium/RemoveDuplicatesFromSortedArray2.java:
--------------------------------------------------------------------------------
1 | package solution.two_pointers.medium;
2 |
3 | /**
4 | * @see Task 80
5 | */
6 | public class RemoveDuplicatesFromSortedArray2 {
7 |
8 | public int removeDuplicates(int[] nums) {
9 | markBadPositions(nums);
10 | int i = 0;
11 | while (i < nums.length && nums[i] != Integer.MIN_VALUE) i++;
12 |
13 | for (int j = i + 1; j < nums.length; j++) {
14 | if (nums[j] != Integer.MIN_VALUE) nums[i++] = nums[j];
15 | }
16 | return i;
17 | }
18 |
19 | /**
20 | * Если элемент повторяется больше 2х раз, то заменяем его на Integer.MIN_VALUE
21 | */
22 | private void markBadPositions(int[] nums) {
23 | int prev = Integer.MIN_VALUE;
24 | int prevCount = 0;
25 | int pos = 0;
26 |
27 | while (pos < nums.length) {
28 | if (nums[pos] != prev) {
29 | prev = nums[pos];
30 | prevCount = 1;
31 | } else {
32 | prevCount++;
33 | }
34 |
35 | if (prevCount > 2) nums[pos] = Integer.MIN_VALUE;
36 | pos++;
37 | }
38 | }
39 |
40 | public int removeDuplicates2(int[] nums) {
41 | if (nums.length == 0) return 0;
42 |
43 | int startIndex = 1;
44 | // count the time of duplicate numbers occurence
45 | int precCounter = 1;
46 |
47 | for (int i = 1; i < nums.length; i++) {
48 | if (nums[i] == nums[i - 1]) {
49 | if (precCounter < 2) {
50 | nums[startIndex++] = nums[i];
51 | }
52 | precCounter++;
53 | } else {
54 | precCounter = 1;
55 | nums[startIndex++] = nums[i];
56 | }
57 | }
58 | return startIndex;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Hello2024_Task2.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Hello2024_Task2 {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | for (int i = 0; i < n; i++) {
55 | int len = sc.nextInt();
56 | char[] chars = sc.nextLine().toCharArray();
57 | int counter = 0;
58 | for (char c : chars) {
59 | if (c == '+') counter++;
60 | else counter--;
61 | }
62 | out.println(Math.abs(counter));
63 | }
64 | out.close();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/easy/PalindromeLinkedList.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.easy;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | /**
6 | * @see Task 234
7 | */
8 | public class PalindromeLinkedList {
9 |
10 | /**
11 | * With two pointers
12 | */
13 | public boolean isPalindrome(ListNode head) {
14 | ListNode slow = head;
15 | ListNode fast = head;
16 | while (fast.next != null && fast.next.next != null) {
17 | slow = slow.next;
18 | fast = fast.next.next;
19 | }
20 |
21 | if (fast.next != null) {
22 | slow = slow.next;
23 | }
24 |
25 | slow = reverse(slow);
26 | fast = head;
27 | while (slow != null) {
28 | if (slow.val != fast.val) {
29 | return false;
30 | }
31 | slow = slow.next;
32 | fast = fast.next;
33 | }
34 | return true;
35 | }
36 |
37 | public ListNode reverse(ListNode head) {
38 | ListNode prev = null;
39 | while (head != null) {
40 | ListNode next = head.next;
41 | head.next = prev;
42 | prev = head;
43 | head = next;
44 | }
45 | return prev;
46 | }
47 |
48 | /**
49 | * With extra memory
50 | */
51 | public boolean isPalindrome_2(ListNode head) {
52 | StringBuilder builder = new StringBuilder();
53 |
54 | while (head != null) {
55 | builder.append(head.val);
56 | head = head.next;
57 | }
58 |
59 | String s = builder.toString();
60 | int start = 0;
61 | int end = s.length() - 1;
62 | while (start < end) {
63 | if (s.charAt(start) != s.charAt(end)) {
64 | return false;
65 | }
66 | start++;
67 | end--;
68 | }
69 | return true;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task4C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.HashMap;
3 | import java.util.Map;
4 | import java.util.StringTokenizer;
5 |
6 | public class Task4C {
7 | public static PrintWriter out;
8 |
9 | private static class MyScanner {
10 | BufferedReader br;
11 | StringTokenizer st;
12 |
13 | public MyScanner() {
14 | br = new BufferedReader(new InputStreamReader(System.in));
15 | }
16 |
17 | String next() {
18 | while (st == null || !st.hasMoreElements()) {
19 | try {
20 | st = new StringTokenizer(br.readLine());
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | return st.nextToken();
26 | }
27 |
28 | int nextInt() {
29 | return Integer.parseInt(next());
30 | }
31 |
32 | long nextLong() {
33 | return Long.parseLong(next());
34 | }
35 |
36 | double nextDouble() {
37 | return Double.parseDouble(next());
38 | }
39 |
40 | String nextLine() {
41 | String str = "";
42 | try {
43 | str = br.readLine();
44 | } catch (IOException e) {
45 | e.printStackTrace();
46 | }
47 | return str;
48 | }
49 | }
50 |
51 | public static void main(String[] args) {
52 | MyScanner sc = new MyScanner();
53 | out = new PrintWriter(new BufferedOutputStream(System.out));
54 |
55 | int n = sc.nextInt();
56 |
57 | Map cache = new HashMap<>();
58 | for (int i = 0; i < n; i++) {
59 | String name = sc.nextLine();
60 |
61 | int counter = cache.containsKey(name) ? cache.get(name) + 1 : 0;
62 | cache.put(name, counter);
63 | out.println(counter == 0 ? "OK" : name + counter);
64 | }
65 |
66 | out.close();
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task466A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task466A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int m = sc.nextInt();
55 | int a = sc.nextInt();
56 | int b = sc.nextInt();
57 |
58 |
59 | out.println(
60 | Math.min(
61 | n * a,
62 | Math.min(
63 | (n / m) * b + (n % m) * a,
64 | ((n / m) + 1) * b
65 | )
66 | )
67 | );
68 |
69 | out.close();
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task327A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task327A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int t = sc.nextInt();
54 |
55 | int curSum = 0;
56 | int maxSum = 0;
57 | int ones = 0;
58 |
59 | for (int i = 0; i < t; i++) {
60 | int v = sc.nextInt();
61 | if (v == 1) ones++;
62 | curSum += v == 0 ? 1 : -1;
63 | if (curSum > maxSum) maxSum = curSum;
64 | if (curSum < 0) curSum = 0;
65 | }
66 |
67 | out.println(maxSum == 0 ? ones - 1 : maxSum + ones);
68 | out.close();
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/binary_search/hard/MedianOfTwoSortedArrays.java:
--------------------------------------------------------------------------------
1 | package solution.binary_search.hard;
2 |
3 | /**
4 | * @see Task 4
5 | */
6 | // TODO check again, spend too much time
7 | public class MedianOfTwoSortedArrays {
8 |
9 | public double findMedianSortedArrays(int[] nums1, int[] nums2) {
10 | if (nums1.length == 0 && nums2.length == 0) return 0;
11 |
12 | if (nums1.length == 0) {
13 | int n = nums2.length;
14 | return nums2[(n - 1) / 2] * 0.5 + nums2[n / 2] * 0.5;
15 | }
16 |
17 | if (nums2.length == 0) {
18 | int n = nums1.length;
19 | return nums1[(n - 1) / 2] * 0.5 + nums1[n / 2] * 0.5;
20 | }
21 |
22 | if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
23 |
24 | // choose shorter to binary search
25 | int n = nums1.length;
26 | int m = nums2.length;
27 | int left = 0;
28 | int right = n;
29 |
30 | // 1,2,3,4
31 | // 2,5,7,8,10
32 | while (left < right) {
33 | int i = (left + right) / 2;
34 | int j = ((n + m) / 2) - i - 1;
35 |
36 | if (nums1[i] < nums2[j]) {
37 | left = i + 1;
38 | } else {
39 | right = i;
40 | }
41 | }
42 |
43 | int first = left;
44 | int second = (n + m) / 2 - left;
45 |
46 | int shorterLeft = first == 0 ? Integer.MIN_VALUE : nums1[first - 1];
47 | int shorterRight = first == n ? Integer.MAX_VALUE : nums1[first];
48 |
49 | int longerLeft = second == 0 ? Integer.MIN_VALUE : nums2[second - 1];
50 | int longerRight = second == m ? Integer.MAX_VALUE : nums2[second];
51 |
52 | if ((n + m) % 2 == 1) {
53 | return Math.min(shorterRight, longerRight);
54 | } else {
55 | return Math.max(shorterLeft, longerLeft) * 0.5 + Math.min(shorterRight, longerRight) * 0.5;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task455A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task455A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | long[] arr = new long[100001];
55 | int value;
56 | for (int i = 0; i < n; i++) {
57 | value = sc.nextInt();
58 | arr[value]++;
59 | }
60 |
61 | long[] temp = new long[100001];
62 | temp[0] = 0;
63 | temp[1] = arr[1];
64 |
65 | for (int i = 2; i <= 100000; i++) {
66 | temp[i] = Math.max(temp[i - 1], temp[i - 2] + arr[i] * i);
67 | }
68 | System.out.println(temp[100000]);
69 |
70 | out.close();
71 | }
72 | }
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task514A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task514A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | String s = sc.nextLine();
54 |
55 | for (int i = 0; i < s.length(); i++) {
56 | int n = Integer.parseInt(String.valueOf(s.charAt(i)));
57 | int r;
58 | if (9 - n >= 0) {
59 | if (9 - n == 0 && i == 0) {
60 | r = n;
61 | } else {
62 | r = Math.min(n, 9 - n);
63 | }
64 | } else {
65 | r = n;
66 | }
67 | out.print(r);
68 | }
69 | out.close();
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/medium/RotateArray.java:
--------------------------------------------------------------------------------
1 | package solution.two_pointers.medium;
2 |
3 | /**
4 | * @see Task 189
5 | */
6 | public class RotateArray {
7 |
8 | public static void main(String[] args) {
9 | rotate(new int[]{1, 2, 3, 4, 5, 6, 7}, 3);
10 | }
11 |
12 | /**
13 | * With two pointer
14 | */
15 | public static void rotate(int[] nums, int k) {
16 | k = k % nums.length;
17 | if (k == 0) return;
18 | int l = 0, r = nums.length - 1;
19 | // in reverse order
20 | reverse(nums, l, r);
21 |
22 | // reverse first part from 0 to [k-1]
23 | l = 0;
24 | r = k - 1;
25 | reverse(nums, l, r);
26 |
27 | // reverse first part from k to the end
28 | l = k;
29 | r = nums.length - 1;
30 | reverse(nums, l, r);
31 |
32 | int a = 0;
33 | }
34 |
35 | private static void reverse(int[] nums, int l, int r) {
36 | while (l < r) {
37 | int tmp = nums[l];
38 | nums[l] = nums[r];
39 | nums[r] = tmp;
40 | l += 1;
41 | r -= 1;
42 | }
43 | }
44 |
45 | public void rotate2(int[] nums, int k) {
46 | if (k == 0) return;
47 | if (k > nums.length) k = k % nums.length;
48 |
49 | for (int i = 0; i < (nums.length / k) - 1; i++) {
50 | for (int j = 0; j < k; j++) {
51 | int i1 = nums.length - 1 - j - i * k;
52 | int i2 = nums.length - 1 - j - k * (i + 1);
53 | nums[i1] = nums[i1] ^ nums[i2];
54 | nums[i2] = nums[i1] ^ nums[i2];
55 | nums[i1] = nums[i1] ^ nums[i2];
56 | }
57 | }
58 |
59 | if (nums.length % k != 0) {
60 | for (int i = 0; i < nums.length - k - 1; i++) {
61 | nums[i] = nums[i + 1] ^ nums[i];
62 | nums[i + 1] = nums[i + 1] ^ nums[i];
63 | nums[i] = nums[i + 1] ^ nums[i];
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task71A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task71A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 |
55 | String[] words = new String[n];
56 | for (int i = 0; i < n; i++) words[i] = sc.nextLine();
57 | for (int i = 0; i < words.length; i++) {
58 | if (words[i].length() <= 10) {
59 | out.println(words[i]);
60 | } else {
61 | out.println(
62 | words[i].charAt(0) + String.valueOf(words[i].length() - 2) + words[i].charAt(words[i].length() - 1)
63 | );
64 | }
65 | }
66 |
67 |
68 | out.close();
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task230A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.*;
3 |
4 | public class Task230A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int s = sc.nextInt();
54 | int n = sc.nextInt();
55 | Queue> pq = new PriorityQueue<>(Comparator.comparing(l -> l.get(0)));
56 | for (int i = 0; i < n; i++) pq.add(Arrays.asList(sc.nextInt(), sc.nextInt()));
57 |
58 | boolean done = true;
59 | while (done && !pq.isEmpty()) {
60 | List dragonInfo = pq.poll();
61 | if (s <= dragonInfo.get(0)) {
62 | done = false;
63 | } else {
64 | s += dragonInfo.get(1);
65 | }
66 | }
67 | out.println(done ? "YES" : "NO");
68 | out.close();
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task189A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task189A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int a = sc.nextInt();
55 | int b = sc.nextInt();
56 | int c = sc.nextInt();
57 |
58 | int max = 0;
59 |
60 | // z = (n - ax - by) / c
61 | for (int x = 0; x <= n / a; x++) {
62 | for (int y = 0; y <= (n - x * a) / b; y++) {
63 | int diff = n - a * x - b * y;
64 | int z = diff / c;
65 | if (diff % c == 0 && x + y + z > max && x * a + y * b + z * c == n) {
66 | max = x + y + z;
67 | }
68 | }
69 | }
70 | out.println(max);
71 | out.close();
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task520B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task520B {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int m = sc.nextInt();
55 |
56 | if (n > m) {
57 | out.println(n - m);
58 | } else {
59 | int counter = 0;
60 | while (n != m) {
61 | if (n > m) {
62 | m += 1;
63 | } else {
64 | if (m % 2 == 0) {
65 | m /= 2;
66 | } else {
67 | m += 1;
68 | }
69 | }
70 | counter++;
71 | }
72 | out.println(counter);
73 | }
74 | out.close();
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task492B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.StringTokenizer;
4 |
5 | public class Task492B {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | int n = sc.nextInt();
55 | int l = sc.nextInt();
56 | int[] a = new int[n];
57 | for (int i = 0; i < n; i++) a[i] = sc.nextInt();
58 |
59 | Arrays.sort(a);
60 |
61 | int maxLen = a[0] * 2;
62 | for (int i = 1; i < a.length; i++) {
63 | if (a[i - 1] == a[i]) continue;
64 | int len = a[i] - a[i - 1];
65 | if (len > maxLen) maxLen = len;
66 | }
67 | int lastLen = (l - a[a.length - 1]) * 2;
68 | if (lastLen > maxLen) maxLen = lastLen;
69 |
70 | out.println(((double) maxLen) / 2);
71 |
72 | out.close();
73 | }
74 |
75 | }
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task118A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.HashSet;
4 | import java.util.Set;
5 | import java.util.StringTokenizer;
6 | import java.util.stream.Collectors;
7 | import java.util.stream.Stream;
8 |
9 | public class Task118A {
10 | public static PrintWriter out;
11 |
12 | private static class MyScanner {
13 | BufferedReader br;
14 | StringTokenizer st;
15 |
16 | public MyScanner() {
17 | br = new BufferedReader(new InputStreamReader(System.in));
18 | }
19 |
20 | String next() {
21 | while (st == null || !st.hasMoreElements()) {
22 | try {
23 | st = new StringTokenizer(br.readLine());
24 | } catch (IOException e) {
25 | e.printStackTrace();
26 | }
27 | }
28 | return st.nextToken();
29 | }
30 |
31 | int nextInt() {
32 | return Integer.parseInt(next());
33 | }
34 |
35 | long nextLong() {
36 | return Long.parseLong(next());
37 | }
38 |
39 | double nextDouble() {
40 | return Double.parseDouble(next());
41 | }
42 |
43 | String nextLine() {
44 | String str = "";
45 | try {
46 | str = br.readLine();
47 | } catch (IOException e) {
48 | e.printStackTrace();
49 | }
50 | return str;
51 | }
52 | }
53 |
54 | public static void main(String[] args) {
55 | MyScanner sc = new MyScanner();
56 | out = new PrintWriter(new BufferedOutputStream(System.out));
57 |
58 | String s = sc.nextLine();
59 | StringBuilder sb = new StringBuilder(s.length());
60 | Set vowels = Stream.of('a', 'o', 'y', 'e', 'u', 'i').map(c -> (int) c).collect(Collectors.toSet());
61 | ;
62 | for (char c : s.toCharArray()) {
63 | char caseC = c;
64 | if (c < 97) caseC = (char) (c + 32);
65 | if (!vowels.contains((int) caseC)) sb.append('.').append(caseC);
66 | }
67 | out.println(sb);
68 | out.close();
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task25A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task25A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int evenCount = 0;
55 | int firstEvenIndex = -1;
56 | int oddCount = 0;
57 | int firstOddIndex = -1;
58 | for (int i = 0; i < n; i++) {
59 | int k = sc.nextInt();
60 | if (evenCount == 0 && k % 2 == 0) firstEvenIndex = i;
61 | if (oddCount == 0 && k % 2 != 0) firstOddIndex = i;
62 | if (k % 2 == 0) evenCount++;
63 | else oddCount++;
64 | if ((evenCount >= 2 && oddCount == 1) || (oddCount >= 2 && evenCount == 1)) break;
65 | }
66 | out.println(evenCount == 1 ? firstEvenIndex + 1 : firstOddIndex + 1);
67 |
68 | out.close();
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/InteractiveTask1.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | /**
5 | * Task
6 | */
7 | public class InteractiveTask1 {
8 | public static PrintWriter out;
9 |
10 | private static class MyScanner {
11 | BufferedReader br;
12 | StringTokenizer st;
13 |
14 | public MyScanner() {
15 | br = new BufferedReader(new InputStreamReader(System.in));
16 | }
17 |
18 | String next() {
19 | while (st == null || !st.hasMoreElements()) {
20 | try {
21 | st = new StringTokenizer(br.readLine());
22 | } catch (IOException e) {
23 | e.printStackTrace();
24 | }
25 | }
26 | return st.nextToken();
27 | }
28 |
29 | int nextInt() {
30 | return Integer.parseInt(next());
31 | }
32 |
33 | long nextLong() {
34 | return Long.parseLong(next());
35 | }
36 |
37 | double nextDouble() {
38 | return Double.parseDouble(next());
39 | }
40 |
41 | String nextLine() {
42 | String str = "";
43 | try {
44 | str = br.readLine();
45 | } catch (IOException e) {
46 | e.printStackTrace();
47 | }
48 | return str;
49 | }
50 | }
51 |
52 | public static void main(String[] args) {
53 | MyScanner sc = new MyScanner();
54 | out = new PrintWriter(new BufferedOutputStream(System.out));
55 |
56 | int i = 0;
57 | boolean done = false;
58 | int l = 1;
59 | int r = 1_000_000;
60 | String sign;
61 | while (!done && i <= 25) {
62 | int m = (l + r) / 2 + 1;
63 | out.println(m);
64 | out.flush();
65 | i++;
66 | sign = sc.nextLine();
67 | if (sign.equals("<")) {
68 | r = m - 1;
69 | } else {
70 | l = m;
71 | }
72 | done = r == l;
73 | }
74 | out.print("! ");
75 | out.print(r);
76 | out.close();
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task363B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task363B {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | int k = sc.nextInt();
55 | int[] h = new int[n];
56 |
57 | int start = 0;
58 | int minSum = Integer.MAX_VALUE;
59 |
60 | int tmpSum = 0;
61 | for (int i = 0; i < n; i++) {
62 | int num = sc.nextInt();
63 | h[i] = num;
64 |
65 | tmpSum += num;
66 | if (i == k - 1) {
67 | minSum = tmpSum;
68 | }
69 | if (i > k - 1) {
70 | tmpSum -= h[i - k];
71 | if (tmpSum < minSum) {
72 | minSum = tmpSum;
73 | start = i - k + 1;
74 | }
75 | }
76 |
77 | }
78 | out.println(start + 1);
79 |
80 | out.close();
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task230B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.HashSet;
3 | import java.util.Set;
4 | import java.util.StringTokenizer;
5 |
6 | public class Task230B {
7 | public static PrintWriter out;
8 |
9 | private static class MyScanner {
10 | BufferedReader br;
11 | StringTokenizer st;
12 |
13 | public MyScanner() {
14 | br = new BufferedReader(new InputStreamReader(System.in));
15 | }
16 |
17 | String next() {
18 | while (st == null || !st.hasMoreElements()) {
19 | try {
20 | st = new StringTokenizer(br.readLine());
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | return st.nextToken();
26 | }
27 |
28 | int nextInt() {
29 | return Integer.parseInt(next());
30 | }
31 |
32 | long nextLong() {
33 | return Long.parseLong(next());
34 | }
35 |
36 | double nextDouble() {
37 | return Double.parseDouble(next());
38 | }
39 |
40 | String nextLine() {
41 | String str = "";
42 | try {
43 | str = br.readLine();
44 | } catch (IOException e) {
45 | e.printStackTrace();
46 | }
47 | return str;
48 | }
49 | }
50 |
51 | public static void main(String[] args) {
52 | MyScanner sc = new MyScanner();
53 | out = new PrintWriter(new BufferedOutputStream(System.out));
54 |
55 | int count = sc.nextInt();
56 | Set set = calcSet();
57 | for (int i = 0; i < count; i++) {
58 | long number = sc.nextLong();
59 | out.println(set.contains(number) ? "YES" : "NO");
60 | }
61 |
62 | out.close();
63 | }
64 |
65 | private static Set calcSet() {
66 | int limit = 1000001;
67 | boolean[] arr = new boolean[limit];
68 | for (int i = 2; i*i < limit; i++) {
69 | if (!arr[i]) {
70 | for (int j = i*i; j < limit; j += i) {
71 | arr[j] = true;
72 | }
73 | }
74 | }
75 | Set set = new HashSet<>();
76 | for (int i = 2; i < limit; i++) if (!arr[i]) set.add((long) i * i);
77 | return set;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task1342A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task1342A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | while (n-- > 0) {
55 | long l = sc.nextInt();
56 | long r = sc.nextInt();
57 |
58 | long priceOne = sc.nextInt();
59 | long priceTwo = sc.nextInt();
60 |
61 | /*
62 | 11 47
63 | 8 101
64 | */
65 | long cost = 0;
66 | if (l != 0 || r != 0) {
67 | if (priceOne * 2 < priceTwo) {
68 | cost += priceOne * (Math.abs(l) + Math.abs(r));
69 | } else {
70 | long min = Math.min(l, r);
71 | cost += priceTwo * min;
72 | l -= min;
73 | r -= min;
74 | cost += Math.max(l, r) * priceOne;
75 | }
76 |
77 | }
78 | out.println(cost);
79 | }
80 |
81 | out.close();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task489B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.StringTokenizer;
4 |
5 | public class Task489B {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | int n = sc.nextInt();
55 | int[] men = new int[n];
56 | for (int i = 0; i < n; i++) {
57 | men[i] = sc.nextInt();
58 | }
59 |
60 | int m = sc.nextInt();
61 | int[] women = new int[m];
62 | for (int i = 0; i < m; i++) {
63 | women[i] = sc.nextInt();
64 | }
65 |
66 | Arrays.sort(men);
67 | Arrays.sort(women);
68 |
69 | int mI = 0, wI = 0;
70 | int pairs = 0;
71 | while (mI < n && wI < m) {
72 | while (wI < m && men[mI] - women[wI] > 1) wI++;
73 | while (mI < n && wI< m && women[wI] - men[mI] > 1) mI++;
74 | if (mI < n && wI< m && Math.abs(men[mI] - women[wI]) <= 1) {
75 | pairs++;
76 | mI++;
77 | wI++;
78 | }
79 | }
80 | out.println(pairs);
81 | out.close();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Hello2024_Task3.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Hello2024_Task3 {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int count = sc.nextInt();
54 | for (int k = 0; k < count; k++) {
55 |
56 | int counter = 0;
57 | int sPrev = Integer.MAX_VALUE;
58 | int tPrev = Integer.MAX_VALUE;
59 |
60 | int n = sc.nextInt();
61 | for (int j = 0; j < n; j++) {
62 | int a = sc.nextInt();
63 | if (a <= sPrev && a <= tPrev) {
64 | if (sPrev <= tPrev) sPrev = a;
65 | else tPrev = a;
66 | } else if (a > sPrev && a > tPrev) {
67 | if (sPrev <= tPrev) sPrev = a;
68 | else tPrev = a;
69 | counter++;
70 | } else if (a > sPrev) {
71 | tPrev = a;
72 | } else {
73 | sPrev = a;
74 | }
75 | }
76 | out.println(counter);
77 | }
78 | out.close();
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task279B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task279B {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 | long t = sc.nextLong();
55 |
56 | int[] a = new int[n];
57 | for (int i = 0; i < n; i++) {
58 | a[i] = sc.nextInt();
59 | }
60 |
61 | int max = 0;
62 | int last = 0;
63 | long tmp = t;
64 | for (int i = 0; i < n; i++) {
65 | if (tmp >= a[i]) {
66 | tmp -= a[i];
67 | } else {
68 | max = Math.max(i - last, max);
69 | if (a[i] > t) {
70 | tmp = t;
71 | last = i + 1;
72 | } else {
73 | while (tmp < a[i] && last <= i) {
74 | tmp += a[last];
75 | last++;
76 | }
77 | tmp -= a[i];
78 | }
79 | }
80 | }
81 | max = Math.max(n - last, max);
82 | out.println(max);
83 |
84 | out.close();
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task433B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.StringTokenizer;
4 |
5 | public class Task433B {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | int n = sc.nextInt();
55 |
56 | long[] v = new long[n];
57 | long[] u = new long[n];
58 |
59 | for (int i = 0; i < n; i++) {
60 | v[i] = sc.nextLong();
61 | u[i] = v[i];
62 | }
63 | Arrays.sort(u);
64 |
65 | long vSum = 0;
66 | long uSum = 0;
67 | for (int i = 0; i < n; i++) {
68 | vSum += v[i];
69 | v[i] = vSum;
70 |
71 | uSum += u[i];
72 | u[i] = uSum;
73 | }
74 |
75 |
76 | int m = sc.nextInt();
77 | for (int i = 0; i < m; i++) {
78 | int t = sc.nextInt();
79 | int l = sc.nextInt();
80 | int r = sc.nextInt();
81 | if (t == 1) {
82 | out.println(v[r - 1] - (l > 1 ? v[l - 2] : 0));
83 | } else {
84 | out.println(u[r - 1] - (l > 1 ? u[l - 2] : 0));
85 | }
86 | }
87 |
88 | out.close();
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/interview-questions/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.example
8 | interview-questions
9 | 1.0-SNAPSHOT
10 |
11 |
12 |
13 | org.springframework.boot
14 | spring-boot-starter-parent
15 | 2.7.10
16 |
17 |
18 |
19 |
20 | 11
21 | 11
22 | 1.16.3
23 | UTF-8
24 |
25 |
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-web
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-data-jdbc
34 |
35 |
36 | org.springframework.boot
37 | spring-boot-starter-test
38 | test
39 |
40 |
41 |
42 | org.apache.httpcomponents
43 | httpclient
44 |
45 |
46 | org.testcontainers
47 | junit-jupiter
48 | ${testcontainers.version}
49 | test
50 |
51 |
52 |
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-maven-plugin
57 |
58 |
59 |
60 |
61 |
62 | central
63 | https://repo.maven.apache.org/maven2
64 |
65 |
66 |
--------------------------------------------------------------------------------
/interview-questions/src/main/java/concurrency/Volatile.java:
--------------------------------------------------------------------------------
1 | package concurrency;
2 |
3 | import java.util.concurrent.atomic.AtomicInteger;
4 | import java.util.function.Consumer;
5 |
6 | /**
7 | * Основная цель volatile - гарантировать, что чтение и запись значения переменной будут атомарными (неделимыми) операциями
8 | * и что изменения, внесенные одним потоком, будут видны другим потокам немедленно. Без использования volatile или
9 | * других механизмов синхронизации, изменения переменной, внесенные одним потоком, могут не отразиться в значениях,
10 | * видимых другим потокам.
11 | *
12 | * ATTENTION: concurrency.Volatile сам по себе не гарантирует атомарности или последовательности операций.
13 | *
14 | * Доп материалы:
15 | * 1. concurrency.Volatile
16 | * 2. Atomic
17 | */
18 |
19 | public class Volatile {
20 |
21 | private static int value = 0;
22 | private static volatile int volatileValue = value;
23 | private static final AtomicInteger atomicInteger = new AtomicInteger(value);
24 |
25 | public static void main(String[] args) throws InterruptedException {
26 | int repeatTime = 1000;
27 | int numberOfThreads = 100;
28 | int expect = repeatTime * numberOfThreads;
29 |
30 | doTheWorkInParallel(repeatTime, numberOfThreads, (index) -> value++);
31 | System.out.printf("Int value: expect = %d, actual = %d\n", expect, value);
32 |
33 | doTheWorkInParallel(repeatTime, numberOfThreads, (index) -> volatileValue++);
34 | System.out.printf("Int volatile value: expect = %d, actual = %d\n", expect, volatileValue);
35 |
36 | doTheWorkInParallel(repeatTime, numberOfThreads, (index) -> atomicInteger.incrementAndGet());
37 | System.out.printf("Atomic int value: expect = %d, actual = %d\n", expect, atomicInteger.get());
38 | }
39 |
40 |
41 | private static void doTheWorkInParallel(
42 | int repeatTime,
43 | int numberOfThreads,
44 | Consumer action
45 | ) throws InterruptedException {
46 |
47 | Runnable runnable = () -> {
48 | for (int i = 0; i < repeatTime; i++) action.accept(i);
49 | };
50 |
51 | Thread[] workers = new Thread[numberOfThreads];
52 | for (int i = 0; i < numberOfThreads; i++) {
53 | workers[i] = new Thread(runnable, String.valueOf(i));
54 | workers[i].start();
55 | }
56 |
57 | for (int j = 0; j < numberOfThreads; j++) workers[j].join();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/greedy/README.md:
--------------------------------------------------------------------------------
1 | ## Теория:
2 |
3 | Жадный алгоритм - это метод, при котором решение строится пошагово, всегда выбирая лучший вариант здесь и сейчас. Таким
4 | образом, задачи, где выбор локально оптимального решения приводит к глобальному оптимальному решению, наиболее подходят
5 | для применения жадного подхода.
6 |
7 | ### Где я смотрел:
8 |
9 | 1. Geeksforgeeks (Много примеров использования) - (https://www.geeksforgeeks.org/greedy-algorithms/)
10 | 2. Статья с визуализацией и задачками на понимание - (https://brilliant.org/wiki/greedy-algorithm/)
11 | 3. Для тех кто любит много теории. "Greedy Algorithms" by Stanford University
12 | 1. Greedy Algorithms Part 1: (https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/13/Small13.pdf)
13 | 2. Greedy Algorithms Part 2: (https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/14/Small14.pdf)
14 | 3. Greedy Algorithms Part 3: (https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/15/Small15.pdf)
15 | 4. Article: (http://web.stanford.edu/class/archive/cs/cs161/cs161.1166/lectures/lecture14.pdf)
16 |
17 | ## Пример
18 |
19 | Задача: [MaximumSubarray.java](medium/MaximumSubarray.java)
20 |
21 | 1. Инициализируем две переменные: **maxSum** и **currentSum**, обе равны первому элементу в массиве.
22 |
23 | 2. Проходим по оставшимся элементам массива, начиная со второго элемента:
24 |
25 | 1. Для каждого элемента:
26 | 2. Обновляем currentSum, добавляя текущий элемент к предыдущей сумме (**currentSum** + текущий элемент).
27 | 3. Если currentSum становится больше текущего значения **maxSum**, обновляем maxSum значением **currentSum**.
28 | 4. Если currentSum становится отрицательным, сбрасываем его в ноль, так как негативная сумма не может быть частью
29 | максимальной подпоследовательности.
30 |
31 | 3. В конце прохода по массиву возвращаем **maxSum**, которая будет содержать максимальную сумму подмассива.
32 |
33 | ```java
34 | class MaximumSubarray {
35 | public int maxSubArray(int[] nums) {
36 | int maxSum = nums[0]; // Инициализация maxSum значением первого элемента
37 | int currentSum = nums[0]; // Инициализация currentSum значением первого элемента
38 |
39 | // Проход по остальным элементам массива
40 | for (int i = 1; i < nums.length; i++) {
41 | // Обновление текущей суммы
42 | currentSum = Math.max(currentSum + nums[i], nums[i]);
43 |
44 | // Обновление максимальной суммы
45 | maxSum = Math.max(maxSum, currentSum);
46 | }
47 |
48 | return maxSum;
49 | }
50 | }
51 |
52 | ```
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task1343C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task1343C {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int t = sc.nextInt();
54 | for (int i = 0; i < t; i++) {
55 | int n = sc.nextInt();
56 |
57 | long sum = 0;
58 | long tmp = 0;
59 | for (int j = 0; j < n; j++) {
60 | int v = sc.nextInt();
61 | if (j == 0) {
62 | tmp = v;
63 | } else {
64 | if (v > 0) {
65 | if (tmp < 0) {
66 | sum += tmp;
67 | tmp = v;
68 | } else if (v > tmp) {
69 | tmp = v;
70 | }
71 | } else {
72 | if (tmp > 0) {
73 | sum += tmp;
74 | tmp = v;
75 | } else if (v > tmp) {
76 | tmp = v;
77 | }
78 | }
79 | }
80 | }
81 | out.println(sum + tmp);
82 | }
83 | out.close();
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/medium/SortList.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.medium;
2 |
3 | import solution.linked_list.ListNode;
4 |
5 | import java.util.PriorityQueue;
6 |
7 | /**
8 | * @see Task 148
9 | */
10 | public class SortList {
11 |
12 | /**
13 | * Merge Sort Implementation
14 | *
15 | * @see Merge Sort article
16 | */
17 | public ListNode sortList(ListNode head) {
18 | if (head == null || head.next == null) return head;
19 |
20 | // split in 2 parts
21 | ListNode left = head;
22 | ListNode right = getMid(head);
23 | ListNode tmp = right.next;
24 | right.next = null;
25 | right = tmp;
26 |
27 | left = sortList(left);
28 | right = sortList(right);
29 | return merge(left, right);
30 | }
31 |
32 | /**
33 | * Find middle with usage slow and fast pointers
34 | */
35 | public ListNode getMid(ListNode head) {
36 | ListNode slow = head, fast = head.next;
37 | while (fast != null && fast.next != null) {
38 | fast = fast.next.next;
39 | slow = slow.next;
40 | }
41 | return slow;
42 | }
43 |
44 | public ListNode merge(ListNode left, ListNode right) {
45 | ListNode dummy = new ListNode();
46 | ListNode tail = dummy;
47 |
48 | while (left != null && right != null) {
49 | if (left.val < right.val) {
50 | tail.next = left;
51 | left = left.next;
52 | } else {
53 | tail.next = right;
54 | right = right.next;
55 | }
56 | tail = tail.next;
57 | }
58 | if (left != null) tail.next = left;
59 | if (right != null) tail.next = right;
60 |
61 | return dummy.next;
62 | }
63 |
64 | /**
65 | * With extra space with usage PriorityQueue
66 | */
67 | public ListNode sortList_2(ListNode head) {
68 | if (head == null || head.next == null) return head;
69 |
70 | PriorityQueue queue = new PriorityQueue<>();
71 | ListNode temp = head;
72 | while (temp.next != null) {
73 | queue.add(temp.val);
74 | temp = temp.next;
75 | }
76 | queue.add(temp.val);
77 | temp = head;
78 | //
79 | while (!queue.isEmpty()) {
80 | temp.val = queue.poll();
81 | temp = temp.next;
82 | }
83 | return head;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task1328C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task1328C {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int t = sc.nextInt();
54 | for (int i = 0; i < t; i++) {
55 | int n = sc.nextInt();
56 | String x = sc.nextLine();
57 | int[] f = new int[x.length()];
58 | int[] s = new int[x.length()];
59 | int min = 0;
60 | int index = 0;
61 | for (char c : x.toCharArray()) {
62 | if (min == 0) {
63 | if (c == '2') {
64 | f[index] = s[index] = 1;
65 | } else if (c == '1') {
66 | min = 1;
67 | f[index] = 1;
68 | s[index] = 0;
69 | } else {
70 | f[index] = s[index] = 0;
71 | }
72 | } else {
73 | f[index] = 0;
74 | s[index] = (int) c - 48;
75 | }
76 | index++;
77 | }
78 | for (int j = 0; j < x.length(); j++) out.print(f[j]);
79 | out.println();
80 | for (int j = 0; j < x.length(); j++) out.print(s[j]);
81 | out.println();
82 | }
83 |
84 | out.close();
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task489C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task489C {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int m = sc.nextInt();
54 | int s = sc.nextInt();
55 |
56 | if (s == 0 && m != 1) {
57 | out.println("-1 -1");
58 | } else {
59 | int restMaxSum = s;
60 | int restMinSum = s;
61 | int[] max = new int[m];
62 | int[] min = new int[m];
63 |
64 | for (int i = 0; i < m; i++) {
65 | int n = Math.min(restMaxSum, 9);
66 | restMaxSum -= n;
67 | max[i] = n;
68 | int k;
69 | if (i == m - 1) {
70 | k = restMinSum;
71 | } else if (restMinSum == 1) {
72 | k = 0;
73 | } else {
74 | k = Math.min(9, restMinSum - 1);
75 | }
76 | restMinSum -= k;
77 | min[m - i - 1] = k;
78 | }
79 |
80 | if (restMaxSum != 0 || restMinSum != 0) {
81 | out.println("-1 -1");
82 | } else {
83 | for (int i = 0; i < m; i++) out.print(min[i]);
84 | out.print(" ");
85 | for (int i = 0; i < m; i++) out.print(max[i]);
86 | }
87 | }
88 | out.close();
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Round_919_Task1.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.HashSet;
3 | import java.util.Set;
4 | import java.util.StringTokenizer;
5 |
6 | public class Round_919_Task1 {
7 | public static PrintWriter out;
8 |
9 | private static class MyScanner {
10 | BufferedReader br;
11 | StringTokenizer st;
12 |
13 | public MyScanner() {
14 | br = new BufferedReader(new InputStreamReader(System.in));
15 | }
16 |
17 | String next() {
18 | while (st == null || !st.hasMoreElements()) {
19 | try {
20 | st = new StringTokenizer(br.readLine());
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | return st.nextToken();
26 | }
27 |
28 | int nextInt() {
29 | return Integer.parseInt(next());
30 | }
31 |
32 | long nextLong() {
33 | return Long.parseLong(next());
34 | }
35 |
36 | double nextDouble() {
37 | return Double.parseDouble(next());
38 | }
39 |
40 | String nextLine() {
41 | String str = "";
42 | try {
43 | str = br.readLine();
44 | } catch (IOException e) {
45 | e.printStackTrace();
46 | }
47 | return str;
48 | }
49 | }
50 |
51 | public static void main(String[] args) {
52 | MyScanner sc = new MyScanner();
53 | out = new PrintWriter(new BufferedOutputStream(System.out));
54 |
55 |
56 | int caseCounter = sc.nextInt();
57 | for (int i = 0; i < caseCounter; i++) {
58 |
59 | int ruleCounter = sc.nextInt();
60 |
61 | long l = 0;
62 | long r = Long.MAX_VALUE;
63 | Set ex = new HashSet<>();
64 | for (int j = 0; j < ruleCounter; j++) {
65 | int ruleNumber = sc.nextInt();
66 | long ruleValue = sc.nextInt();
67 | if (ruleNumber == 1) {
68 | l = Math.max(ruleValue, l);
69 | } else if (ruleNumber == 2) {
70 | r = Math.min(ruleValue, r);
71 | } else {
72 | ex.add(ruleValue);
73 | }
74 | }
75 |
76 | long result;
77 | if (r < l) result = 0;
78 | else if (r == l) {
79 | result = ex.contains(r) ? 0 : 1;
80 | } else {
81 | long finalL = l;
82 | long finalR = r;
83 | result = r - l + 1 - ex.stream().filter(e -> e >= finalL && e <= finalR).count();
84 | }
85 |
86 | out.println(result);
87 | }
88 | out.close();
89 | }
90 | }
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task122A.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 |
4 | public class Task122A {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | public static void main(String[] args) {
50 | MyScanner sc = new MyScanner();
51 | out = new PrintWriter(new BufferedOutputStream(System.out));
52 |
53 | int n = sc.nextInt();
54 |
55 | int i = n;
56 | boolean r = i % 10 == 4 || i % 10 == 7;
57 | while (r && i != 0) {
58 | if (i % 10 != 4 && i % 10 != 7) {
59 | r = false;
60 | break;
61 | }
62 | i = i / 10;
63 | }
64 |
65 | if (!r) {
66 | int d = 4;
67 | while (d < n) {
68 | if (n % d == 0) {
69 | r = true;
70 | break;
71 | }
72 |
73 | int newD = 0;
74 | int j = 0;
75 | boolean inc = false;
76 |
77 | while (d != 0) {
78 | int k = d % 10;
79 | if (j == 0 || inc) {
80 | newD += (int) (Math.pow(10, j) * (k == 4 ? 7 : 4));
81 | inc = k == 7;
82 | } else {
83 | newD += (int) (Math.pow(10, j) * (k == 4 ? 4 : 7));
84 | }
85 | j++;
86 | d = d / 10;
87 | }
88 |
89 | if (inc) newD += (int) (Math.pow(10, j) * 4);
90 | d = newD;
91 | }
92 | }
93 |
94 | out.println(r ? "YES" : "NO");
95 |
96 | out.close();
97 | }
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task580C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.*;
3 | import java.util.stream.Collectors;
4 |
5 | public class Task580C {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | int n = sc.nextInt();
55 | int m = sc.nextInt();
56 |
57 | int[] cats = new int[n];
58 | for (int i = 0; i < cats.length; i++) cats[i] = sc.nextInt();
59 |
60 | List[] edges = new ArrayList[n];
61 | for (int i = 0; i < edges.length; i++) edges[i] = new ArrayList<>();
62 |
63 | for (int i = 0; i < n - 1; i++) {
64 | int s = sc.nextInt() - 1;
65 | int e = sc.nextInt() - 1;
66 | edges[s].add(e);
67 | edges[e].add(s);
68 | }
69 |
70 | int rest = 0;
71 |
72 | Queue q = new LinkedList<>();
73 | q.add(0);
74 |
75 | int[] catsCounter = new int[n];
76 | boolean[] visited = new boolean[n];
77 |
78 | while (!q.isEmpty()) {
79 | int node = q.poll();
80 | if (visited[node]) continue;
81 | visited[node] = true;
82 | int prev = cats[node] == 1 ? catsCounter[node] + 1 : 0;
83 | if (prev > m) continue;
84 |
85 | List children = edges[node].stream().filter(c -> !visited[c]).collect(Collectors.toList());
86 | if (children.isEmpty()) {
87 | rest++;
88 | } else {
89 | q.addAll(children);
90 | for (Integer child : children) catsCounter[child] = prev;
91 | }
92 | }
93 |
94 | out.print(rest);
95 | out.close();
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/heap/README.md:
--------------------------------------------------------------------------------
1 | Алгоритмы на основе кучи (**heap**) и **PriorityQueue** (очередь с приоритетом) являются важными инструментами в области
2 | алгоритмического программирования и структур данных. Они обеспечивают эффективное управление элементами в соответствии с
3 | их приоритетом.
4 |
5 | Куча (**heap**) - это специальная структура данных, представляющая собой полное бинарное дерево, где каждый узел имеет
6 | значение, которое не меньше (или не больше, в зависимости от типа кучи) значений его дочерних узлов. Куча может быть
7 | реализована как массив, где индексы элементов соответствуют их позиции в дереве.
8 |
9 | **PriorityQueue** - это абстрактная структура данных, основанная на куче. Она предоставляет интерфейс для добавления
10 | элементов с определенным приоритетом и извлечения элемента с наивысшим приоритетом. PriorityQueue использует кучу для
11 | эффективного управления приоритетами элементов.
12 |
13 | Преимущества использования алгоритмов на основе кучи(**heap**) и **PriorityQueue**:
14 |
15 | 1. Упорядоченное извлечение: Алгоритмы на основе кучи и PriorityQueue позволяют извлекать элементы в порядке их
16 | приоритета. Наивысший приоритетный элемент всегда доступен с минимальной (в случае мин-кучи) или максимальной (в
17 | случае макс-кучи) задержкой времени.
18 |
19 | 2. Эффективность: Куча обеспечивает эффективное добавление и удаление элементов с временной сложностью O(log n), где n -
20 | количество элементов в куче. Это делает алгоритмы на основе кучи и PriorityQueue быстрыми и масштабируемыми.
21 |
22 | 3. Гибкость: Куча и PriorityQueue могут использоваться для решения различных задач, таких как сортировка, поиск
23 | наибольших или наименьших элементов, планирование задач и др. Они предоставляют гибкую основу для разработки
24 | эффективных алгоритмов.
25 |
26 | Примеры задач, решаемых с использованием кучи и PriorityQueue:
27 |
28 | - Сортировка: Куча может использоваться для реализации алгоритмов сортировки, таких как сортировка кучей (Heap Sort).
29 | - Поиск k наибольших/наименьших элементов: Куча и PriorityQueue позволяют эффективно найти k наибольших или наименьших
30 | элемент
31 |
32 | Пример:
33 | Задача: Kth Largest Element in an Array [KthLargestElementInAnArray.java](medium/KthLargestElementInAnArray.java)
34 |
35 | Условие задачи: Дан массив целых чисел `nums` и целое число `k`. Найдите значение `k`-го наибольшего элемента в массиве.
36 |
37 | Пример решения на Java:
38 |
39 | ```java
40 | import java.util.PriorityQueue;
41 |
42 | class Solution {
43 | public int findKthLargest(int[] nums, int k) {
44 | // Создаем мин-кучу (PriorityQueue)
45 | Queue heap = new PriorityQueue<>();
46 |
47 | for (int n : nums) {
48 | heap.add(n); // добавляем элемент
49 | if (heap.size() > k) heap.poll(); // если кол-во элементов больше k, то можно удалить минимальный из них
50 | }
51 |
52 | return heap.peek();
53 | }
54 | }
55 | ```
56 |
57 | Приведенное решение имеет временную сложность O(n log k), где n - размер массива, а k - требуемая статистика порядка.
--------------------------------------------------------------------------------
/algorithms/src/main/java/Round_919_Task2.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.StringTokenizer;
4 |
5 | public class Round_919_Task2 {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 |
55 | int caseNumbers = sc.nextInt();
56 | for (int i = 0; i < caseNumbers; i++) {
57 | int arrSize = sc.nextInt();
58 | int[] arr = new int[arrSize];
59 |
60 | int maxDropNumber = sc.nextInt();
61 | int maxNegativeNumber = sc.nextInt();
62 |
63 | int arrSum = 0;
64 |
65 | for (int j = 0; j < arrSize; j++) {
66 | arr[j] = sc.nextInt();
67 | arrSum += arr[j];
68 | }
69 | Arrays.sort(arr);
70 |
71 |
72 | int r = arrSize - maxDropNumber;
73 | int maxSum = 0;
74 | int c = 0;
75 | for (int j = r - 1; j >= 0; j--) {
76 | if (c == maxNegativeNumber) {
77 | maxSum += arr[j];
78 | } else {
79 | maxSum -= arr[j];
80 | c++;
81 | }
82 | }
83 |
84 | int l = r - maxNegativeNumber;
85 | int tmpSum = maxSum;
86 | while (r < arrSize) {
87 | tmpSum -= arr[r];
88 | if (l >= 0) tmpSum += 2 * arr[l];
89 | l++;
90 | r++;
91 | maxSum = Math.max(maxSum, tmpSum);
92 | }
93 |
94 | out.println(maxSum);
95 | }
96 |
97 | out.close();
98 | }
99 | }
100 |
101 | /*
102 |
103 | 6 4
104 | 1 2 3 3 3 4 5 8 9 200
105 |
106 |
107 | 1 2 3 3 [3] | 4 5 8 9 200
108 |
109 | */
110 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task158B.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Arrays;
3 | import java.util.StringTokenizer;
4 |
5 | public class Task158B {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | int[] s = new int[sc.nextInt()];
55 | for (int i = 0; i < s.length; i++) {
56 | s[i] = sc.nextInt();
57 | }
58 | Arrays.sort(s);
59 | int start = 0;
60 | int end = s.length - 1;
61 | int counter = 0;
62 |
63 | while (start < s.length && end >= 0 && end >= start && s[end] == 4) {
64 | counter++;
65 | end--;
66 | }
67 |
68 |
69 | // 3 and 1
70 | while (start < s.length && end >= 0 && end >= start && s[end] == 3 && s[start] == 1) {
71 | counter++;
72 | start++;
73 | end--;
74 | }
75 |
76 | // 3 without 1
77 | while (start < s.length && end >= 0 && end >= start && s[end] == 3) {
78 | counter++;
79 | end--;
80 | }
81 |
82 | while (start < s.length && end >= 0 && end >= start && s[end] == 2 && s[start] == 1) {
83 | if (start + 1 <= end && s[start + 1] == 1) start++;
84 | counter++;
85 | start++;
86 | end--;
87 | }
88 |
89 | // only 1
90 | if (start < s.length && end >= 0 && end >= start && s[end] == 1 && s[start] == 1) {
91 | int num = end - start + 1;
92 | counter += num / 4;
93 | if (num % 4 != 0) counter++;
94 | end = start - 1;
95 | }
96 |
97 | // only 2
98 | while (start < s.length && end >= 0 && end >= start) {
99 | counter++;
100 | start++;
101 | end--;
102 | }
103 |
104 | out.println(counter);
105 | out.close();
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task5C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.Stack;
3 | import java.util.StringTokenizer;
4 |
5 | public class Task5C {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | MyScanner sc = new MyScanner();
52 | out = new PrintWriter(new BufferedOutputStream(System.out));
53 |
54 | String s = sc.nextLine();
55 |
56 | Stack stack = new Stack<>();
57 | int tmpSum = 0;
58 | char[] arr = s.toCharArray();
59 | char c;
60 | int lastOpenBracketIndex = -1;
61 | for (int i = 0; i < arr.length; i++) {
62 | c = arr[i];
63 | if (c == '(') {
64 | stack.push(i);
65 | if (tmpSum != 0) {
66 | for (int j = lastOpenBracketIndex; j < i; j++) arr[j] = '+';
67 | tmpSum = 0;
68 | }
69 | } else {
70 | if (!stack.isEmpty()) {
71 | lastOpenBracketIndex = stack.pop();
72 | tmpSum += 2;
73 | } else {
74 | if (tmpSum != 0) {
75 | for (int j = lastOpenBracketIndex; j < i; j++) arr[j] = '+';
76 | tmpSum = 0;
77 | }
78 | }
79 | }
80 | }
81 | if (tmpSum != 0) {
82 | for (int j = lastOpenBracketIndex; j < arr.length; j++) arr[j] = '+';
83 | }
84 |
85 | int max = 0;
86 | int counter = 0;
87 |
88 | tmpSum = 0;
89 | for (char value : arr) {
90 | if (value == '+') tmpSum++;
91 | else {
92 | if (tmpSum != 0) {
93 | if (tmpSum > max) {
94 | max = tmpSum;
95 | counter = 1;
96 | } else if (tmpSum == max) {
97 | counter += 1;
98 | }
99 | }
100 | tmpSum = 0;
101 | }
102 | }
103 | if (tmpSum != 0) {
104 | if (tmpSum > max) {
105 | max = tmpSum;
106 | counter = 1;
107 | } else if (tmpSum == max) {
108 | counter += 1;
109 | }
110 | }
111 |
112 | out.print(max);
113 | out.print(' ');
114 | out.print(counter == 0 ? 1 : counter);
115 | out.close();
116 | }
117 | }
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/linked_list/medium/DesignLinkedList.java:
--------------------------------------------------------------------------------
1 | package solution.linked_list.medium;
2 |
3 | /**
4 | * @see Task 707
5 | */
6 | class DesignLinkedList {
7 |
8 | public class MyLinkedList {
9 |
10 | class Link {
11 | Link prev;
12 | Link next;
13 | int value;
14 |
15 | public Link(int value) {
16 | this.value = value;
17 | }
18 | }
19 |
20 | /**
21 | * Initialize your data structure here.
22 | */
23 | Link head;
24 | Link tail;
25 | int size;
26 |
27 | public MyLinkedList() {
28 | head = new Link(Integer.MIN_VALUE);
29 | tail = new Link(Integer.MAX_VALUE);
30 | head.next = tail;
31 | tail.prev = head;
32 | }
33 |
34 | /**
35 | * Get the value of the index-th node in the linked list. If the index is invalid, return -1.
36 | */
37 | public int get(int index) {
38 | if (index < 0 || index >= size) {
39 | return -1;
40 | }
41 |
42 | Link current = head;
43 | while (index-- >= 0) {
44 | current = current.next;
45 | }
46 | return current.value;
47 | }
48 |
49 | /**
50 | * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
51 | */
52 | public void addAtHead(int val) {
53 | Link link = new Link(val);
54 |
55 | head.next.prev = link;
56 | link.next = head.next;
57 |
58 | head.next = link;
59 | link.prev = head;
60 | size++;
61 | }
62 |
63 | /**
64 | * Append a node of value val to the last element of the linked list.
65 | */
66 | public void addAtTail(int val) {
67 | Link link = new Link(val);
68 | //<--
69 | tail.prev.next = link;
70 | link.prev = tail.prev;
71 | //-->
72 | link.next = tail;
73 | tail.prev = link;
74 | size++;
75 | }
76 |
77 | /**
78 | * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater
79 | * than the length, the node will not be inserted.
80 | */
81 | public void addAtIndex(int index, int val) {
82 | if (index < 0 || index > size) {
83 | return;
84 | } else if (index == 0) {
85 | addAtHead(val);
86 | return;
87 | } else if (index == size) {
88 | addAtTail(val);
89 | return;
90 | }
91 |
92 | Link current = head;
93 | Link link = new Link(val);
94 | while (index-- > 0) {
95 | current = current.next;
96 | }
97 |
98 | link.next = current.next;
99 | current.next.prev = link;
100 |
101 | current.next = link;
102 | link.prev = current;
103 |
104 | size++;
105 | }
106 |
107 | /**
108 | * Delete the index-th node in the linked list, if the index is valid.
109 | */
110 | public void deleteAtIndex(int index) {
111 | if (index < 0 || index >= size) {
112 | return;
113 | }
114 |
115 | Link current = head;
116 | while (index-- >= 0) {
117 | current = current.next;
118 | }
119 |
120 | current.prev.next = current.next;
121 | current.next.prev = current.prev;
122 | size--;
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Hello2024_Task4.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.StringTokenizer;
3 | import java.util.TreeSet;
4 |
5 | public class Hello2024_Task4 {
6 | public static PrintWriter out;
7 |
8 | private static class MyScanner {
9 | BufferedReader br;
10 | StringTokenizer st;
11 |
12 | public MyScanner() {
13 | br = new BufferedReader(new InputStreamReader(System.in));
14 | }
15 |
16 | String next() {
17 | while (st == null || !st.hasMoreElements()) {
18 | try {
19 | st = new StringTokenizer(br.readLine());
20 | } catch (IOException e) {
21 | e.printStackTrace();
22 | }
23 | }
24 | return st.nextToken();
25 | }
26 |
27 | int nextInt() {
28 | return Integer.parseInt(next());
29 | }
30 |
31 | long nextLong() {
32 | return Long.parseLong(next());
33 | }
34 |
35 | double nextDouble() {
36 | return Double.parseDouble(next());
37 | }
38 |
39 | String nextLine() {
40 | String str = "";
41 | try {
42 | str = br.readLine();
43 | } catch (IOException e) {
44 | e.printStackTrace();
45 | }
46 | return str;
47 | }
48 | }
49 |
50 | static class Element implements Comparable {
51 | Element next;
52 | Element prev;
53 | int id;
54 | int value;
55 |
56 | public Element(int id, int value) {
57 | this.id = id;
58 | this.value = value;
59 | }
60 |
61 | public void setNext(Element next) {
62 | this.next = next;
63 | if (next != null) next.prev = this;
64 | }
65 |
66 | public void setPrev(Element prev) {
67 | this.prev = prev;
68 | if (prev != null) prev.next = this;
69 | }
70 |
71 | @Override
72 | public int compareTo(Element other) {
73 | if (this.value != other.value) {
74 | return Integer.compare(this.value, other.value);
75 | }
76 | return Integer.compare(this.id, other.id);
77 | }
78 |
79 | }
80 |
81 | public static void main(String[] args) {
82 | MyScanner sc = new MyScanner();
83 | out = new PrintWriter(new BufferedOutputStream(System.out));
84 |
85 | int n = sc.nextInt();
86 | for (int i = 0; i < n; i++) {
87 | int len = sc.nextInt();
88 | TreeSet treeSet = new TreeSet<>();
89 | Element prev = null;
90 | for (int j = 0; j < len; j++) {
91 | int val = sc.nextInt();
92 | Element element = new Element(j, val);
93 | treeSet.add(element);
94 | if (prev != null) element.setPrev(prev);
95 | prev = element;
96 | }
97 |
98 | boolean failed = false;
99 | for (int j = 0; j < len - 1; j++) {
100 | Element maxEl = treeSet.pollLast();
101 | if (maxEl.value == 0) {
102 | failed = true;
103 | break;
104 | }
105 | if (
106 | (maxEl.next != null && maxEl.next.value >= maxEl.value - 1) ||
107 | (maxEl.prev != null && maxEl.prev.value >= maxEl.value - 1)
108 | ) {
109 | if (maxEl.next != null) {
110 | maxEl.next.setPrev(maxEl.prev);
111 | } else {
112 | maxEl.prev.setNext(maxEl.next);
113 | }
114 | } else {
115 | failed = true;
116 | break;
117 | }
118 | }
119 | out.println(failed || treeSet.size() != 1 || treeSet.pollLast().value != 0 ? "NO" : "YES");
120 | }
121 | out.close();
122 | }
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/algorithms/src/main/java/Task20C.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.util.*;
3 |
4 | public class Task20C {
5 | public static PrintWriter out;
6 |
7 | private static class MyScanner {
8 | BufferedReader br;
9 | StringTokenizer st;
10 |
11 | public MyScanner() {
12 | br = new BufferedReader(new InputStreamReader(System.in));
13 | }
14 |
15 | String next() {
16 | while (st == null || !st.hasMoreElements()) {
17 | try {
18 | st = new StringTokenizer(br.readLine());
19 | } catch (IOException e) {
20 | e.printStackTrace();
21 | }
22 | }
23 | return st.nextToken();
24 | }
25 |
26 | int nextInt() {
27 | return Integer.parseInt(next());
28 | }
29 |
30 | long nextLong() {
31 | return Long.parseLong(next());
32 | }
33 |
34 | double nextDouble() {
35 | return Double.parseDouble(next());
36 | }
37 |
38 | String nextLine() {
39 | String str = "";
40 | try {
41 | str = br.readLine();
42 | } catch (IOException e) {
43 | e.printStackTrace();
44 | }
45 | return str;
46 | }
47 | }
48 |
49 | static long[] distance;
50 | static long INF = Long.MAX_VALUE;
51 |
52 | static int[] parents;
53 |
54 | static List[] edges;
55 | static boolean[] visited;
56 |
57 | static class Edge {
58 | int number;
59 | long weight;
60 |
61 | public Edge(int number, long weight) {
62 | this.number = number;
63 | this.weight = weight;
64 | }
65 | }
66 |
67 | public static void main(String[] args) {
68 | MyScanner sc = new MyScanner();
69 | out = new PrintWriter(new BufferedOutputStream(System.out));
70 |
71 | int n = sc.nextInt();
72 | int m = sc.nextInt();
73 |
74 | distance = new long[n + 1];
75 | parents = new int[n + 1];
76 | edges = new ArrayList[n + 1];
77 | visited = new boolean[n + 1];
78 |
79 | for (int i = 1; i < distance.length; i++) {
80 | distance[i] = INF;
81 | edges[i] = new ArrayList<>();
82 | }
83 |
84 | for (int i = 0; i < m; i++) {
85 | int s = sc.nextInt();
86 | int e = sc.nextInt();
87 | long w = sc.nextLong();
88 | edges[s].add(new Edge(e, w));
89 | edges[e].add(new Edge(s, w));
90 | }
91 |
92 | if (dijkstra(1, n)) {
93 | StringBuilder ans = new StringBuilder();
94 | List path = new ArrayList<>();
95 |
96 | for (int e = n; e != -1; e = parents[e])
97 | path.add(e);
98 |
99 | // reversing path
100 | for (int i = path.size() - 1; i >= 0; i--) {
101 | ans.append(path.get(i)).append(" ");
102 | }
103 | out.println(ans);
104 | } else {
105 | out.print("-1");
106 | }
107 |
108 |
109 | out.close();
110 | }
111 |
112 | private static boolean dijkstra(int start, int end) {
113 | Queue pq = new PriorityQueue<>(Comparator.comparingLong(a -> a.weight));
114 | pq.add(new Edge(start, 0));
115 | parents[start] = -1;
116 | distance[start] = 0;
117 |
118 | while (!pq.isEmpty()) {
119 | Edge from = pq.poll();
120 | int s = from.number;
121 | visited[s] = true;
122 | if (s == end) return true;
123 |
124 | for (Edge to : edges[s]) {
125 | int e = to.number;
126 | long w = to.weight;
127 | if (!visited[e] && distance[s] + w < distance[e]) {
128 | distance[e] = distance[s] + w;
129 | pq.add(new Edge(e, distance[e]));
130 | parents[e] = s;
131 | }
132 | }
133 | }
134 |
135 | return false;
136 | }
137 |
138 | }
--------------------------------------------------------------------------------
/algorithms/src/main/java/solution/two_pointers/README.md:
--------------------------------------------------------------------------------
1 | # Two pointers
2 |
3 | The two pointers algorithm is a popular technique used in computer science and programming for solving various problems
4 | efficiently. It involves using **two pointers** that traverse a data structure simultaneously, usually from different
5 | starting points or at different speeds, to solve the problem at hand.
6 |
7 | The basic idea behind the two pointers algorithm is to reduce the time complexity of a problem by avoiding redundant
8 | computations. By using **two pointers**, we can often achieve a linear - _O(n)_ or sub-linear - _O(const * n)_ runtime
9 | complexity, compared to a naive
10 | approach that would require nested loops or multiple iterations.
11 |
12 | The two pointers are typically initialized to different positions in the data structure and then updated based on
13 | certain conditions. These conditions can be defined according to the requirements of the problem being solved. As the
14 | pointers move through the data structure, they narrow down the search space or perform specific operations until the
15 | desired result is obtained.
16 |
17 | The two pointers algorithm is commonly used for solving problems such as:
18 |
19 | 1. Array manipulation: For example, finding a pair of elements in an array that satisfies a specific condition, such as
20 | the
21 | sum being equal to a target value. The two pointers can start from the beginning and end of the array and move
22 | towards
23 | each other until the desired pair is found.
24 |
25 | 2. String manipulation: In problems involving strings, the two pointers can be used to compare characters or search for
26 | patterns. For instance, in palindrome-related problems, two pointers can start from the beginning and end of the
27 | string
28 | and check if the characters match.
29 |
30 | 3. Linked list traversal: When working with linked lists, two pointers can be employed to traverse the list at different
31 | speeds, allowing operations like cycle detection or finding the middle element efficiently.
32 |
33 | 4. Searching and sorting: The two pointers algorithm can also be utilized for searching or sorting problems. For
34 | instance,
35 | in binary search, two pointers can be used to define the search range and update them based on the comparison of the
36 | target element with the middle element.
37 |
38 | ## Example 1: Finding a pair of elements with a sum equal to a target in a sorted array.
39 |
40 | ```java
41 | public class TwoPointersExample {
42 | public static int[] findPairWithTargetSum(int[] nums, int targetSum) {
43 | int left = 0; // Left pointer
44 | int right = nums.length - 1; // Right pointer
45 |
46 | while (left < right) {
47 | int currentSum = nums[left] + nums[right];
48 |
49 | if (currentSum == targetSum) {
50 | return new int[]{nums[left], nums[right]}; // Pair found
51 | } else if (currentSum < targetSum) {
52 | left++; // Increase the left pointer to increase the sum
53 | } else {
54 | right--; // Decrease the right pointer to decrease the sum
55 | }
56 | }
57 |
58 | return new int[0]; // Pair not found
59 | }
60 |
61 | public static void main(String[] args) {
62 | int[] nums = {2, 5, 8, 12, 30};
63 | int targetSum = 20;
64 |
65 | int[] result = findPairWithTargetSum(nums, targetSum);
66 |
67 | if (result.length == 2) {
68 | System.out.println("Pair found: " + result[0] + ", " + result[1]);
69 | } else {
70 | System.out.println("Pair not found.");
71 | }
72 | }
73 | }
74 | ```
75 |
76 | In this example, using the Two Pointers algorithm, we are looking for a pair of elements in a sorted array whose sum is
77 | equal to a target value. We initialize the **left** pointer **left** to the start of the array and the **right** pointer right to
78 | the end of the array. Then, we compare the sum of the elements pointed to by **left** and **right** with targetSum. If the sum
79 | is equal to targetSum, we return the found pair. If the sum is less than targetSum, we increment **left** to increase the
80 | sum. If the sum is greater than targetSum, we decrement **right** to decrease the sum. The process continues until **left**
81 | becomes greater than or equal to **right** (indicating no pair is found) or until a pair with the sum targetSum is found.
82 |
--------------------------------------------------------------------------------
/interview-questions/src/main/java/concurrency/concurrent-base.md:
--------------------------------------------------------------------------------
1 | # Оглавление
2 |
3 | ## Что такое потоки и процессы?
4 |
5 | ### Что такое процесс?
6 |
7 | Процесс в компьютерной системе представляет собой выполнение программы и является основной единицей для запуска
8 | программ. В Java, когда мы запускаем программу, на самом деле запускается процесс Java Virtual Machine (JVM), а основной
9 | поток, в котором выполняется основная функция программы, является одним из потоков в этом процессе, известным как
10 | основной поток.
11 | Представим это на примере. При запуске программы в операционной системе, например, в Windows, создается соответствующий
12 | процесс, который может быть наблюдаем в диспетчере задач. Этот процесс представляет собой выполнение программы
13 | (например, запуск .exe-файла).
14 | В случае Java-программы, процесс **JVM** (*Java Virtual Machine*) запускается, когда мы запускаем программу. Внутри
15 | процесса JVM создается основной поток, который выполняет основную функцию программы. Он может быть рассмотрен как
16 | основная нить исполнения внутри процесса JVM. Основной поток является точкой входа для выполнения программы и может
17 | порождать дополнительные потоки исполнения при необходимости.
18 | Таким образом, процесс в Java представляет собой выполнение программы, а основной поток является потоком исполнения
19 | внутри этого процесса, который выполняет основную функцию программы.
20 |
21 | ### Что такое поток?
22 |
23 | Потоки являются более мелкими единицами выполнения по сравнению с процессами. Процесс может порождать несколько потоков
24 | во время своего выполнения. В отличие от процессов, несколько потоков одного процесса совместно используют ресурсы кучи
25 | и области методов процесса. Однако каждый поток имеет свой собственный программный счетчик, стек виртуальной машины и
26 | локальный стек методов.
27 | При переключении между потоками нагрузка на систему намного меньше, чем при переключении между процессами. Поэтому
28 | потоки также называются легковесными процессами. Программы на Java, по своей сути, являются многопоточными программами,
29 | и мы можем использовать *Java Management Extensions* (**JMX**), чтобы увидеть, какие потоки присутствуют в обычной
30 | Java-программе.
31 | Вот пример кода, который позволяет нам получить информацию о потоках в Java:
32 |
33 | ```java
34 | import java.lang.management.ManagementFactory;
35 | import java.lang.management.ThreadInfo;
36 | import java.lang.management.ThreadMXBean;
37 |
38 | public class ThreadExample {
39 | public static void main(String[] args) {
40 | // Получаем экземпляр ThreadMXBean
41 | ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
42 |
43 | // Получаем информацию о потоках
44 | ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
45 |
46 | // Выводим информацию о каждом потоке
47 | for (ThreadInfo threadInfo : threadInfos) {
48 | System.out.println("Thread ID: " + threadInfo.getThreadId());
49 | System.out.println("Thread Name: " + threadInfo.getThreadName());
50 | System.out.println("Thread State: " + threadInfo.getThreadState());
51 | System.out.println("===========================");
52 | }
53 | }
54 | }
55 | ```
56 |
57 | В этом примере мы используем `ThreadMXBean`, который предоставляет методы для управления и мониторинга потоков в Java.
58 | Метод `dumpAllThreads(false, false)` возвращает информацию о всех потоках в системе. Затем мы выводим информацию о
59 | каждом потоке, такую как его идентификатор (**ID**), имя и состояние.
60 |
61 | Этот пример поможет нам лучше понять, какие потоки существуют в обычной Java-программе и как можно использовать Java
62 | Management Extensions для их анализа и мониторинга.
63 |
64 | ---
65 |
66 | ### Разница между синхронными и асинхронными вызовами
67 |
68 | 1. Синхронная обработка: после выполнения вызова происходит ожидание результата, и вызывающая сторона не продолжает
69 | выполнение до получения результата.
70 | 2. Асинхронная обработка: после выполнения вызова происходит немедленное возвращение, и
71 | вызывающая сторона может продолжить свою работу без ожидания результата возврата.
72 |
73 | ### Зачем использовать многопоточность?
74 |
75 | Поток можно рассматривать как легковесный процесс, являющийся наименьшей единицей выполнения программы. Переключение и
76 | планирование между потоками имеют гораздо меньшие накладные расходы по сравнению с процессами. С развитием многоядерных
77 | процессоров, несколько потоков могут выполняться одновременно, что позволяет снизить накладные расходы на переключение
78 | контекста потока. С точки зрения современных требований Интернета: Современные системы требуют миллионы или даже десятки
79 | миллионов параллельных операций, и многопоточное параллельное программирование является фундаментом для разработки
80 | высокопараллельных систем. Эффективное использование механизмов многопоточности может значительно повысить общий уровень
81 | параллелизма, возможности и производительность системы.
82 |
83 | ### Жизненный цикл потока
84 |
85 | Поток в Java может находиться в одном из следующих 6 различных состояний:
86 |
87 | 1. NEW - начальное состояние, когда поток создан, но метод `start()` ещё не вызван.
88 | 2. RUNNABLE - состояние выполнения, когда поток готов к выполнению и ожидает запуска.
89 | 3. BLOCKED - состояние блокировки, когда поток ожидает разблокировки ресурса или монитора.
90 | 4. WAITING - состояние ожидания, когда поток ожидает, пока другой поток выполнит определенные действия, такие как
91 | уведомление или прерывание.
92 | 5. TIME_WAITING - состояние ожидания с тайм-аутом, когда поток ожидает определенное время, после чего возвращается в
93 | RUNNABLE состояние.
94 | 6. TERMINATED - состояние завершения, когда выполнение потока завершено.
95 |
96 | 
97 |
98 | ### Пул потоков
99 |
100 | Пул потоков представляет собой набор ресурсов, который управляет группой потоков, позволяя ограничивать и управлять ими.
101 | Каждый пул потоков также предоставляет базовую статистику, такую как количество выполненных задач.
102 | Вот краткое описание преимуществ использования пулов потоков:
103 |
104 | 1. Экономия ресурсов: Пул потоков позволяет снизить расход ресурсов путем повторного использования созданных потоков,
105 | вместо создания и уничтожения потоков каждый раз при выполнении задачи. Это сокращает затраты на создание и
106 | уничтожение потоков.
107 | 2. Повышение отзывчивости: При поступлении задачи ее можно немедленно выполнить с использованием уже существующего
108 | потока из пула, вместо ожидания создания нового потока. Это улучшает отзывчивость системы.
109 | 3. Управляемость потоками: Потоки являются ценными ресурсами, и их неограниченное создание может привести к исчерпанию
110 | системных ресурсов и снижению стабильности системы. Использование пула потоков позволяет единообразно распределять,
111 | настраивать и мониторить потоки.
112 |
113 | Пул потоков обычно используется для выполнения нескольких независимых трудоемких задач. Без использования
114 | многопоточности задачи выполняются последовательно. Однако, при использовании пула потоков, несколько независимых задач
115 | могут выполняться параллельно, что повышает эффективность выполнения задач.
116 |
117 | ### Executor diagram
118 |
119 | 
--------------------------------------------------------------------------------