Загрузка...

1920. Build Array from Permutation | Leetcode Daily 6 May 2025 | Java | Hindi

*"1920. Build Array from Permutation"* is a medium-level problem and the LeetCode daily challenge (POTD) for 5 May 2025. The solution, written in Java, is explained with a dry-run on a blackboard, making it accessible to viewers with diverse programming backgrounds by focusing on the logic rather than language-specific details.

*Intuition:*
The problem asks us to build a new array such that ans[i] = nums[nums[i]] using the original array nums. A naive solution would require creating a new array, thus using extra space. However, we can cleverly modify the original array in-place using a technique that temporarily encodes both the old and new values in each index. The key idea here is to store two values in one integer without losing the original — we take advantage of the fact that all values are in the range 0 to n-1, so multiplying by n lets us shift one value into the higher digits.

During the first loop, we update nums[i] to store both the original value and the desired new value: nums[i] = nums[i] + n * (nums[nums[i]] % n). The modulo ensures we only use the original value (in case nums[nums[i]] was already updated). Then, in the second loop, we divide each element by n to extract just the new value we want, discarding the original. This trick gives us an efficient in-place solution with O(n) time and O(1) extra space, which is a smart and elegant use of number encoding.

Link to the problem: https://leetcode.com/problems/build-array-from-permutation/description/

Link to the Java Code: https://github.com/AditiChourasia/Leetcode-Solutions-AlgorithmHQ/blob/main/1920.%20Build%20Array%20from%20Permutation/Original.java

For doubts/queries, please reach out on aditichourasia10@gmail.com
Connect with me on Linkedin: https://www.linkedin.com/in/aditi-chourasia-a2a572121/

Other problems for practice:

https://youtu.be/hCZcdBvm12o
https://youtu.be/Nx1TW2htTWY
https://youtu.be/EXwj-h5K8dc
https://youtu.be/BdSKfarrnE4
https://youtu.be/hD0Kn58m6Kw
https://youtu.be/SMMIe2eaHSo
https://youtu.be/I9ij7JY1klc
https://youtu.be/4WM8_1mTD9A

#leetcodejava #leetcode #dailychallenge #potd #hindi

Видео 1920. Build Array from Permutation | Leetcode Daily 6 May 2025 | Java | Hindi канала AlgorithmHQ
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять