<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mariia Honcharenko on Medium]]></title>
        <description><![CDATA[Stories by Mariia Honcharenko on Medium]]></description>
        <link>https://medium.com/@mmmaariieee?source=rss-2e0da5bf7c87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-sob_XCzC3Bmq6b-X3k1Uw.jpeg</url>
            <title>Stories by Mariia Honcharenko on Medium</title>
            <link>https://medium.com/@mmmaariieee?source=rss-2e0da5bf7c87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:10:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mmmaariieee/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Technical interviews: Max Profit With K Transactions]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-max-profit-with-k-transactions-bfcf13b104e6?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfcf13b104e6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technical-interview]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 06:16:37 GMT</pubDate>
            <atom:updated>2023-02-20T06:16:37.600Z</atom:updated>
            <content:encoded><![CDATA[<p>(solution in JavaScript)</p><p>You’re given an array of positive integers representing the prices of a single stock on various days. You’re also given an integer k, which represents the number of transactions you’re allowed to make. One transaction consists of buying the stock on a given day and selling it on another, later day.</p><p>Write a function that returns the maximum profit that you can make by buying and selling the stock, given k transactions (note that you can only hold one share of the stock at a time).</p><pre>// Input: prices = [5, 11, 3, 50, 60, 90]<br>  //      k = 2<br><br><br>// Expected output: 93<br>  // Buy: 5, Sell: 11; Buy: 3, Sell: 90</pre><p><strong>Solution</strong></p><p>Firstly, let’s create maxProfitWithKTransactions function which takes prices and k as parameters. Let’s also create some variables.</p><pre>function maxProfitWithKTransactions(prices, k) {<br>  <br>  // creating variables to store the array of previous profits,<br>  // the number of current row, and the array of current profits<br>  let prevProfits = prices.map(p =&gt; 0);<br>  let currentRow = 1;<br>  let currentProfits = [];<br>}</pre><p>Next, let’s create a while loop and add some new variables inside.</p><pre>function maxProfitWithKTransactions(prices, k) {<br>  <br>  // creating variables to store the array of previous profits,<br>  // the number of current row, and the array of current profits<br>  let prevProfits = prices.map(p =&gt; 0);<br>  let currentRow = 1;<br>  let currentProfits = [];<br><br>  // while the number of current row is less than the k value<br>  while (currentRow &lt;= k) {<br><br>    // assigning current profits to 0<br>    currentProfits = [0];<br><br>    // assigning the lagrgest potential profit to the first value of prices array with a negative sign<br>    let largestPotentialProfit = -prices[0];<br>  }<br>}</pre><p>Inside of while loop, let’s define a for loop that will check every price in prices array, compare potential profit with the current one, and push the larger one to the currentProfits array.</p><pre>function maxProfitWithKTransactions(prices, k) {<br>  <br>  // creating variables to store the array of previous profits,<br>  // the number of current row, and the array of current profits<br>  let prevProfits = prices.map(p =&gt; 0);<br>  let currentRow = 1;<br>  let currentProfits = [];<br><br>  // while the number of current row is less than the k value<br>  while (currentRow &lt;= k) {<br><br>    // assigning current profits to 0<br>    currentProfits = [0];<br><br>    // assigning the lagrgest potential profit to the first value of prices array with a negative sign<br>    let largestPotentialProfit = -prices[0];<br><br>    // iterating through the array of prices<br>    for (let i = 1; i &lt; prices.length; i++) {<br><br>      // creating the variable of potential profit and assigning it to difference between the element from previous profits array and the element from prices array<br>      let potentialProfit = prevProfits[i] - prices[i];<br><br>      // if the value of potential profit is greater than the value of largest potential profit, reasigning the last one<br>      largestPotentialProfit = potentialProfit &gt; largestPotentialProfit ? potentialProfit : largestPotentialProfit;<br><br>      // creating the variable of current profit and asigning it to the new value, if it is larger than the previous one<br>      let currentProfit = Math.max(prices[i] + largestPotentialProfit, currentProfits[i-1]);<br><br>      // pushing current profit value to the array of current profits<br>      currentProfits.push(currentProfit);<br>    }<br>  }<br>}</pre><p>Outside of for loop, we need to increase the value of currentRow and reassign previous profits to current ones. Finally, outside of while loop, return the last value of the current profits’ array.</p><pre>function maxProfitWithKTransactions(prices, k) {<br>  <br>  // creating variables to store the array of previous profits,<br>  // the number of current row, and the array of current profits<br>  let prevProfits = prices.map(p =&gt; 0);<br>  let currentRow = 1;<br>  let currentProfits = [];<br><br>  // while the number of current row is less than the k value<br>  while (currentRow &lt;= k) {<br><br>    // assigning current profits to 0<br>    currentProfits = [0];<br><br>    // assigning the lagrgest potential profit to the first value of prices array with a negative sign<br>    let largestPotentialProfit = -prices[0];<br><br>    // iterating through the array of prices<br>    for (let i = 1; i &lt; prices.length; i++) {<br><br>      // creating the variable of potential profit and assigning it to difference between the element from previous profits array and the element from prices array<br>      let potentialProfit = prevProfits[i] - prices[i];<br><br>      // if the value of potential profit is greater than the value of largest potential profit, reasigning the last one<br>      largestPotentialProfit = potentialProfit &gt; largestPotentialProfit ? potentialProfit : largestPotentialProfit;<br><br>      // creating the variable of current profit and asigning it to the new value, if it is larger than the previous one<br>      let currentProfit = Math.max(prices[i] + largestPotentialProfit, currentProfits[i-1]);<br><br>      // pushing current profit value to the array of current profits<br>      currentProfits.push(currentProfit);<br>    }<br>    <br>    // increasing the value of current row<br>    currentRow++;<br><br>    // reasigning previous profits to current profits<br>    prevProfits = currentProfits;<br>  }<br>  <br>  // returning the last value of current profits array<br>  return currentProfits[currentProfits.length - 1];<br>}</pre><p>I hope this post was useful for you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfcf13b104e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews: Node Depths]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-node-depths-aa2a86e4a028?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa2a86e4a028</guid>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 21:31:05 GMT</pubDate>
            <atom:updated>2023-02-06T21:31:05.416Z</atom:updated>
            <content:encoded><![CDATA[<p>(solution in JavaScript)</p><p>The distance between a node in a Binary Tree and the tree’s root is called the node’s depth.</p><p>Write a function that takes in a Binary Tree and returns the sum of it node’s depths.</p><pre>// Input: tree =   1<br>  //             /   \<br>  //            2     3<br>  //           / \   / \<br>  //          4   5 6   7<br>  //         / \<br>  //        8   9<br><br><br>// Expected output: 16<br>  // The depth of the node with value 2 is 1.<br>  // The depth of the node with value 3 is 1.<br>  // The depth of the node with value 4 is 2.<br>  // The depth of the node with value 5 is 2.<br>  // Etc..<br>  // the Summ of all the depths is 16.</pre><p><strong>Solution</strong></p><p>Firstly, let’s create nodeDepths function which takes root of the Binary Tree as a parameter. Let’s create a variable which will store the value of the sum.</p><pre>function nodeDepths(root) {<br><br>  // creating a variable to store depths sum<br>  let sum = 0;<br>}</pre><p>Next, let’s create a recursive function inside of nodeDepths function with the parameters that are going to be reassigned every time that recursive function is called.</p><pre>function nodeDepths(root) {<br><br>  let sum = 0;<br><br>  // creating a variable to store depths sum<br>  function recursive(node = root, depth = 0) {<br>  }<br>}</pre><p>If node parameter doesn’t equal to null , a function will call itself twice for left and right nodes. The depth variable will be increased by 1 every time recursive function is called and it will be added to sum variable in the end.</p><pre>function nodeDepths(root) {<br><br>  let sum = 0;<br><br>  function recursive(node = root, depth = 0) {<br><br>    // if node doesn&#39;t equal null<br>    if (node !== null) {<br><br>      // calling recursive function for the left node and increasing depth by 1<br>      recursive(node.left, depth + 1);<br><br>      // calling recursive function for the left node and increasing depth by 1<br>      recursive(node.right, depth + 1);<br><br>      // adding depth to the sum variable<br>      sum += depth;<br>    }<br>  }<br>}</pre><p>After declaring the recursive function, let’s call it. We will return sum variable in the end.</p><pre>function nodeDepths(root) {<br><br>  let sum = 0;<br><br>  function recursive(node = root, depth = 0) {<br><br>    if (node !== null) {<br><br>      recursive(node.left, depth + 1);<br>      recursive(node.right, depth + 1);<br><br>      sum += depth;<br>    }<br>  }<br><br>  // calling recursive function<br>  recursive();<br><br>  // returning sum variable<br>  return sum;<br><br>}</pre><p>You can learn more about recursive functions by the link below:</p><p><a href="https://www.geeksforgeeks.org/binary-tree-data-structure/">Binary Tree Data Structure - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa2a86e4a028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews: Nth Fibonacci]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-nth-fibonacci-3eecf5052c9?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eecf5052c9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[fibonacci]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 03:51:07 GMT</pubDate>
            <atom:updated>2023-01-30T03:51:07.231Z</atom:updated>
            <content:encoded><![CDATA[<p>(2 different solutions in JavaScript)</p><p>The Fibonacci sequence is defined as follows: the first number of the sequence is 0, the second number is 1, and the nth number is the sum of the (n - 1) th and (n - 2) th numbers. Write a function that takes in an integer n and returns the n th Fibonacci number.</p><p>First few numbers of Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8..</p><p>We are going to use zero-indexing for the series.</p><pre>// Input: n = 0<br>// Expected output: 0<br><br>// Input: n = 2<br>// Expected output: 1<br><br>// Input: n = 6<br>// Expected output: 8</pre><p><strong>Solution №1</strong></p><p>Firstly, let’s create a fibonacci function. If n is less than 2, function should return n .</p><pre>function fibonacci(num) {<br><br>  // if num is 0 or 1, return itself<br>  if (num &lt; 2) {<br>    return num;<br>  }<br>}</pre><p>To store the values of 2 previous numbers, let’s create a variable.</p><pre>function fibonacci(num) {<br><br>  if (num &lt; 2) {<br>    return num;<br>  }<br><br>  // create a variable to store last 2 numbers<br>  let lastTwo = [0, 1];<br>}</pre><p>While iterating through all the numbers before given n , the function should calculate a sum of last 2 numbers, and reassign the values of the variable.</p><pre>function fibonacci(num) {<br><br>  if (num &lt; 2) {<br>    return num;<br>  }<br><br>  let lastTwo = [0, 1];<br><br>  // iterate through all the numbers less than (num - 1)<br>  for (let i = 0; i &lt; num - 1; ++i) {<br><br>   // calculate a sum of last 2 numbers<br>   const sum = lastTwo[0] + lastTwo[1];<br><br>   // reassign new values to last 2 numbers<br>   lastTwo = [lastTwo[1], sum];<br>  }<br>}</pre><p>Finally, return last number from the variable lastTwo .</p><pre>function fibonacci(num) {<br><br>  if (num &lt; 2) {<br>    return num;<br>  }<br><br>  let lastTwo = [0, 1];<br><br>  for (let i = 0; i &lt; num - 1; ++i) {<br><br>   const sum = lastTwo[0] + lastTwo[1];<br>   lastTwo = [lastTwo[1], sum];<br><br>  // return last number<br>  return lastTwo[1];<br>  }<br>}</pre><p><strong>Solution №2. Recursive</strong></p><p>The recursive solution is shorter. The first step is the same. If n is less than 2, function should return n .</p><pre>function fibonacci(num) {<br><br>  // if num is 0 or 1, return itself<br>  if (num &lt; 2) {<br>    return num;<br>  }<br>}</pre><p>After that, function should return a sum of 2 fibonacci functions called recursively with (n - 1) and (n - 2) parameters.</p><pre>function fibonacci(num) {<br><br>  if (num &lt; 2) {<br>    return num;<br>  }<br><br>  // calculate each of two last n&#39;s separately with recursion and make a sum<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>}</pre><p>You can learn more about recursive functions by the link below:</p><p><a href="https://www.geeksforgeeks.org/recursive-functions/">Recursive Functions - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eecf5052c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews: shift Linked List]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-shift-linked-list-573f1ac7e767?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/573f1ac7e767</guid>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 05:35:00 GMT</pubDate>
            <atom:updated>2023-01-30T02:58:39.093Z</atom:updated>
            <content:encoded><![CDATA[<p>(Solution in JavaScript)</p><p>In the given Linked List, shift all the elements by k positions, and return its new head.</p><p>Shifting a Linked List means moving its nodes forward or backward and wrapping them around the list where appropriate. Whether nodes are moved forward or backward is determined by whether k is positive or negative.</p><p>You can assume that Linked List will always have at least one node (the head will never be null ).</p><pre>// Input: head = 0 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5<br>//        k = 2<br><br>// Expected output: 4 -&gt; 5 -&gt; 0 -&gt; 1 -&gt; 2 -&gt; 3</pre><p><strong>Solution</strong></p><p>Firstly, let’s create all the necessary variables.</p><pre>function shiftLinkedList(head, k) {<br><br>  // variable i to traverse through the Linked List to shift it<br>  let i = 0;<br><br>  // variable c to count the amount of elements<br>  let c = 1;<br><br>  // variable node for the current node while traversing through the Linked List<br>  let node = head;<br>  <br>  // variable newNode to store the value of the head of the shifted Linked List<br>  let newHead = head;<br><br>  // variable last to store the value of the last node of the shifted Linked List<br>  let last = head;<br>}</pre><p>Before shifting the Linked List, we should count its length. To do so, let’s create a while loop, which will increase value of c by one with every loop until the value of the ext node is equal null .</p><pre>function shiftLinkedList(head, k) {<br><br>  let i = 0;<br>  let c = 1;<br>  let node = head;<br>  let newHead = head;<br>  let last = head;<br><br>  // while node.next doesn&#39;t equal null<br>  while (node.next) {<br>    // reassign the value of variable node to the next node<br>    node = node.next;<br>    // increase the value of c by 1<br>    c++;<br>  }<br><br>  // after while loop, reassign the value of variable node to head again<br>  node = head;<br><br>}</pre><p>To avoid shifting elements several loops if k is bigger than the length of the Linked List, let’s find a module.</p><pre>function shiftLinkedList(head, k) {<br><br>  let i = 0;<br>  let c = 1;<br>  let node = head;<br>  let newHead = head;<br>  let last = head;<br><br>  while (node.next) {<br>    node = node.next;<br>    c++;<br>  }<br><br>  node = head;<br><br>  // find module k of c<br>  k %= c;<br><br>}</pre><p>If k is equal 0, it means that the Linked List is not supposed to be shifted.</p><pre>function shiftLinkedList(head, k) {<br><br>  let i = 0;<br>  let c = 1;<br>  let node = head;<br>  let newHead = head;<br>  let last = head;<br><br>  while (node.next) {<br>    node = node.next;<br>    c++;<br>  }<br><br>  node = head;<br><br>  k %= c;<br><br>  // if parameter k is equal 0<br>  if (k === 0) {<br>    // return head of given Linked List<br>    return head;<br>  }<br>}</pre><p>Let’s create another while loop which traverses through Linked List and finds the last element of the shifted Linked List.</p><pre>function shiftLinkedList(head, k) {<br><br>  let i = 0;<br>  let c = 1;<br>  let node = head;<br>  let newHead = head;<br>  let last = head;<br><br>  while (node.next) {<br>    node = node.next;<br>    c++;<br>  }<br><br>  node = head;<br><br>  k %= c;<br><br>  if (k === 0) {<br>    return head;<br>  }<br><br>  // while node.next doesn&#39;t equal null<br>  while (node.next) {<br>    // reassign the value of variable node to the next node<br>    node = node.next;<br>    // increase the value of i by 1<br>    i++;<br><br>    // while k is positive and i is bigger than k<br>    if (k &gt; 0 &amp;&amp; i &gt; k) {<br>      // reassign the value of the last node to the next node of the previous &#39;last&#39;<br>      last = last.next;<br>    }<br><br>    // if k is negative and sum of k and i is equal -1<br>    if (k &lt; 0 &amp;&amp; i + k === -1) {<br>      // assign value of the &#39;last&#39; to current node<br>      last = node;<br>    }<br>  }<br>}</pre><p>Now, when we know the value of last element of the shifted Linked List, lets fix the connections between elements.</p><pre>function shiftLinkedList(head, k) {<br><br>  let i = 0;<br>  let c = 1;<br>  let node = head;<br>  let newHead = head;<br>  let last = head;<br><br>  while (node.next) {<br>    node = node.next;<br>    c++;<br>  }<br><br>  node = head;<br><br>  k %= c;<br><br>  if (k === 0) {<br>    return head;<br>  }<br><br>  while (node.next) {<br>    node = node.next;<br>    i++;<br><br>    if (k &gt; 0 &amp;&amp; i &gt; k) {<br>      last = last.next;<br>    }<br><br>    if (k &lt; 0 &amp;&amp; i + k === -1) {<br>      last = node;<br>    }<br>  }<br><br>  // the next element of &#39;last&#39; becomes a new head of shifted Linked List<br>  newHead = last.next;<br>  <br>  // the head of the original Linked List becomes the next element of the last one from the original Linked List<br>  node.next = head;<br><br>  // assign the next element of the last one from the shifted Linked List to null<br>  last.next = null;<br><br>  // return head of the shifted Linked List<br>  return newHead;<br><br>}</pre><p>You can learn more about Linked List in JavaScript by the link below:</p><p><a href="https://www.geeksforgeeks.org/implementation-linkedlist-javascript/">Implementation of LinkedList in Javascript - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=573f1ac7e767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews: find shortest string]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-find-shortest-string-9b068880c838?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b068880c838</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technical-interview]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 04:31:28 GMT</pubDate>
            <atom:updated>2023-01-16T04:31:28.075Z</atom:updated>
            <content:encoded><![CDATA[<p>(Solution in JavaScript)</p><p>From the Array of strings, return the shortest string. If there is more than one string of the shortest length, return the string that comes first in the array.</p><pre>// Input: [&#39;abc&#39;, &#39;ab&#39;, &#39;a&#39;, &#39;abcd&#39;]<br><br>// Expected output: &#39;a&#39;</pre><p><strong>Solution №1</strong></p><p>Firstly, let’s create a variable to store an index of the shortest element.</p><pre>function findShortestString(arr) {<br><br>  // create a variable to store an index of the shortest value<br>  let shortestInx = 0;<br><br>}</pre><p>Then, iterate through the whole array and if the length of the element is less than the length of the value on the stored index, reassign index of the shortest element to the index of the current element.</p><pre>function findShortestString(arr) {<br><br>  let shortestInx = 0;<br><br>  // iterate through the array<br>  for (let i = 0; i &lt; arr.length; i++) {<br><br>    // if current value length is less than the length of arr[shortestInx]<br>    if (arr[i].length &lt; arr[shortestInx].length) {<br><br>      // reassign the shortestInx to the index of current value<br>      shortestInx = i;<br>    }<br>  }<br>}</pre><p>After for loop, return a value of the shortest element.</p><pre>function findShortestString(arr) {<br><br>  let shortestInx = 0;<br><br>  for (let i = 0; i &lt; arr.length; i++) {<br><br>    if (arr[i].length &lt; arr[shortestInx].length) {<br><br>      shortestInx = i;<br>    }<br>  }<br><br>  return arr[shortestInx];<br><br>}</pre><p><strong>Solution №2</strong></p><p>Solution number 2 includes using .reduce() method. This method will the first parameter to store the shortest value and the second parameter to compare the current value to the stored shortest one.</p><pre>function findShortestString(arr) {<br><br>  return arr.reduce((shortest, string) =&gt; <br>    string.length &lt; shortest.length ? string : shortest);<br>}</pre><p>You can learn more about .reduce() method by the link below:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.prototype.reduce() - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b068880c838" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical interviews: fix the string by removing the repetitions]]></title>
            <link>https://medium.com/@mmmaariieee/technical-interviews-fix-the-string-by-removing-the-repetitions-20886a93599?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/20886a93599</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 02:40:02 GMT</pubDate>
            <atom:updated>2023-01-09T02:40:02.808Z</atom:updated>
            <content:encoded><![CDATA[<p>(Solution in Ruby)</p><p>You are given a string with lowercase and uppercase letter, and some of them are repeated twice. To fix the string, you need to remove any adjacent pairs of characters in which:</p><ul><li>the characters are the same letter, and;</li><li>one is uppercase and the other is lowercase.</li></ul><pre># Input: &quot;cCcodDdinNngkK&quot;<br><br># Expected output: &quot;coding&quot;</pre><p><strong>Solution</strong></p><p>Firstly, to iterate through letters, let’s split the given string into an array. Also, we need to create a new empty array to store “good” letters that satisfy the requirements of the problem.</p><pre>def fix_the_string(str)<br><br>    # turn a string into an array<br>    arr = str.split(&#39;&#39;)<br><br>    # create new empty array<br>    newarr = []<br><br>end</pre><p>Next, we create a for loop to iterate through each letter.</p><pre>def fix_the_string(str)<br><br>    arr = str.split(&#39;&#39;)<br>    newarr = []<br><br>    # create a for loop<br>    for each in arr do<br><br>    end<br><br>end</pre><p>Inside the for loop, we need to write an ‘if’ statement, which will sort letters. If:</p><ul><li>newarr is not empty;</li><li>the letter from arr ISN’T equal to the last letter from newarr ;</li><li>the letter from arr, uppercased, IS equal to the last letter from newarr, uppercased as well;</li></ul><p>we need to pop this letter from newarr, to avoid any adjacent pairs.</p><pre>def fix_the_string(str)<br><br>    arr = str.split(&#39;&#39;)<br>    newarr = []<br><br>    for each in arr do<br><br>      # remove letter from newarr if it meets the requirements<br>      if !newarr.empty? &amp;&amp; each != newarr.last &amp;&amp;  each.upcase == newarr.last.upcase<br>            newarr.pop<br>      end<br><br>    end<br><br>end</pre><p>Else, if the letter is not included , we will push it to newarr.</p><pre>def fix_the_string(str)<br><br>    arr = str.split(&#39;&#39;)<br>    newarr = []<br><br>    for each in arr do<br><br>      if !newarr.empty? &amp;&amp; each != newarr.last &amp;&amp;  each.upcase == newarr.last.upcase<br>            newarr.pop<br>      else<br>            # push the letter to newarr<br>            newarr.push(each)<br>      end<br><br>    end<br><br>end</pre><p>Finally, to return a fixed string, we need to join the array of the ‘good’ letters.</p><pre>def fix_the_string(str)<br>    arr = str.split(&#39;&#39;)<br>    newarr = []<br><br>    for each in arr do<br>        if !newarr.empty? &amp;&amp; each != newarr.last &amp;&amp;  each.upcase == newarr.last.upcase<br>            newarr.pop<br>        else<br>            newarr.push(each)<br>        end<br>    end<br><br><br>    # return a joined newarr<br>    fixed_str = newarr.join(&#39;&#39;)<br>end</pre><p><strong>Complexity</strong></p><pre># The time complexity for both iterating through the string and popping elements off the stack is O(n).<br># Time: O(n)<br><br># We create a stack variable to hold the &quot;good&quot; characters and a string variable to hold the result, that&#39;s why a complexity is O(n).<br># Space: O(n)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20886a93599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails: how to seed data with Faker]]></title>
            <link>https://medium.com/@mmmaariieee/ruby-on-rails-how-to-seed-data-with-faker-694c4fb60b46?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/694c4fb60b46</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 04:40:49 GMT</pubDate>
            <atom:updated>2023-01-02T04:40:49.653Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are creating your API in Ruby, you will need to have some “default” data to test your project. You can seed data in seeds.rb file. To save some time, you can use Faker to get some random information.</p><ul><li>Firstly, you need to include Faker gem in Gemfile .</li></ul><pre># Gemfile<br><br>gem &#39;faker&#39;</pre><ul><li>Let’s imagine we have 2 models: User and Card , where Card belongs to User and User has only one Cart.</li></ul><pre># user.rb<br><br>class User &lt; ApplicationRecord<br>    has_one :cart, dependent: :destroy<br>end</pre><pre># cart.rb<br><br>class Cart &lt; ApplicationRecord<br>  belongs_to :user<br>end</pre><ul><li>Then, in seeds.rb we need to include destroy function in the beginning of the file to clear our database every time we reseed it.</li></ul><pre># seeds.rb<br><br>User.destroy_all<br>Cart.destroy_all</pre><ul><li>If you are using unique values from the generator that has a limited number of potential values, you should clear the record of unique values that have been returned.</li></ul><pre># seeds.rb<br><br>User.destroy_all<br>Cart.destroy_all<br><br>Faker::UniqueGenerator.clear</pre><ul><li>Let’s write a function to seed data for User model. You can browse all the sections of Faker information on the <a href="https://github.com/faker-ruby/faker">Faker GitHub page</a>.</li></ul><pre># seeds.rb<br><br>puts &quot;Seeding users...&quot;<br>10.times {User.create(first_name: Faker::Name.first_name,<br>                      last_name: Faker::Name.last_name,<br>                      username: Faker::Internet.username,<br>                      email: Faker::Internet.free_email,<br>                      phone_number: Faker::PhoneNumber.cell_phone,<br>                      password_digest: Faker::Internet.password)}</pre><ul><li>If you want to seed some information for a model that includes a foreign key, you will need to write each function for the model with a primary key, and for each instance, create an instance of the model with a foreign key.</li></ul><pre># seeds.rb<br><br>puts &quot;Adding carts to users ...&quot;<br>User.all.each do |u|<br>    Cart.create(user: u)<br>end</pre><p>To learn more, read Faker Library documentation:</p><p><a href="https://github.com/faker-ruby/faker">GitHub - faker-ruby/faker: A library for generating fake data such as names, addresses, and phone numbers.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=694c4fb60b46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures in Ruby: reverse Doubly Linked List]]></title>
            <link>https://medium.com/@mmmaariieee/data-structures-in-ruby-how-to-reverse-doubly-linked-list-929cdb4063d0?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/929cdb4063d0</guid>
            <category><![CDATA[technical-interview]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 00:16:04 GMT</pubDate>
            <atom:updated>2023-01-30T02:58:03.195Z</atom:updated>
            <content:encoded><![CDATA[<p>Reversing Linked Lists is one of the common problems among Data Structures exercises. To work on the reversing method for Linked List, firstly we need to create a LinkedList class. To make it easier for us, we will create a Node class first, which will help create a Linked List later.</p><p>In node.rb we are going to create a Node class, which has value, next_node, and prev_node attributes.</p><pre>class Node<br>  attr_accessor :value, :next_node, :prev_node<br><br>  def initialize(value, next_node = nil, prev_node = nil)<br>    @value = value<br>    @next_node = next_node<br>    @prev_node = prev_node<br>  end<br>end</pre><p>To use a Node class while creating a Linked List class, we will need to require Node.rb in LinkedList.rb.</p><pre>require_relative &#39;./node&#39;</pre><p>We are going to create a Linked List class, which has head, tail, and length attributes.</p><pre>class LinkedList<br>  attr_accessor :head, :tail, :length<br><br>  def initialize<br>    @head = nil<br>    @tail = nil<br>    @length = 0<br>  end<br>end</pre><p>To keep track of the length, we need to define a push method, which will be able to add new nodes to the liked list.</p><pre>def push(value)<br>    new_node = Node.new(value)<br>end</pre><p>If the length of the linked list is 0, it means it has neither a head nor a tail. So we will assign a newly created node to both head and tail attributes.</p><pre>def push(value)<br>    new_node = Node.new(value)<br>    if @length==0<br>      @head = new_node<br>      @tail = new_node<br>    end<br>  end</pre><p>If the length of the linked list is not 0, it already has a head and a tail. So now we need to assign the next node after the tail to a newly created node and the previous node of the newly created one to the tail. Finally, we are reassigning the tail to the newly created node.</p><pre>def push(value)<br>    new_node = Node.new(value)<br>    if @length==0<br>      @head = new_node<br>      @tail = new_node<br>    else <br>      @tail.next_node = new_node<br>      new_node.prev_node = @tail<br>      @tail = new_node<br>    end<br>  end</pre><p>To keep track of the length of the linked list, we are going to increase the variable by 1 every time the function is executed.</p><pre>def push(value)<br>    new_node = Node.new(value)<br>    if @length==0<br>      @head = new_node<br>      @tail = new_node<br>    else <br>      @tail.next_node = new_node<br>      new_node.prev_node = @tail<br>      @tail = new_node<br>    end<br>    @length += 1<br>    return self<br>  end</pre><p>Let’s create a reverse method.</p><p>If the length of the linked list is less than 2, it means that only one node is a head and a tail at the same time. So the linked list will look the same even if we reverse it.</p><pre>def reverse<br>    return self if @length &lt; 2<br>end</pre><p>If the length is more than 1, we will need to reverse a linked list.</p><p>Firstly, let’s swap head and tail. We can do it using an additional variable node.</p><pre>def reverse<br>    return self if @length &lt; 2<br>    node = @head<br>    @head = @tail<br>    @tail = node<br>end</pre><p>Secondly, we need to change the order of the nodes. To do so, we need to iterate through all the nodes of the linked list, and for each of them, swap the previous node and the next node. To make sure we iterated through all of the nodes, we need to add an i variable.</p><pre>def reverse<br>    return self if @length &lt; 2<br>    node = @head<br>    @head = @tail<br>    @tail = node<br>    i = 0<br>    while i&lt;@length do<br>        prev = node.next_node<br>        node.next_node = node.prev_node<br>        node.prev_node = prev<br>        node = prev<br>        i += 1<br>    end<br>end</pre><p>Finally, we return our reversed linked list back.</p><pre>def reverse<br>    return self if @length &lt; 2<br>    node = @head<br>    @head = @tail<br>    @tail = node<br>    i = 0<br>    while i&lt;@length do<br>        prev = node.next_node<br>        node.next_node = node.prev_node<br>        node.prev_node = prev<br>        node = prev<br>        i += 1<br>    end<br>    return self<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929cdb4063d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Splat Operator in Ruby]]></title>
            <link>https://medium.com/@mmmaariieee/splat-operator-in-ruby-ad4a6e2d7b4?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4a6e2d7b4</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 05:05:45 GMT</pubDate>
            <atom:updated>2022-12-12T05:05:45.353Z</atom:updated>
            <content:encoded><![CDATA[<p>The * ‘splat’ operator in Ruby is used for situations when you don’t know in advance how many arguments will a method take. Starting from Ruby 2.0 ‘splat’ operator can be single or double.</p><p><strong>Single </strong><strong>* operator, </strong>for example:</p><pre>def puts_numbers(*nums)<br>    num1, num2 = nums<br>    puts &quot;num1: #{num1}, num2: #{num2}&quot;<br>end</pre><p>*nums are just the parameters passed to the method puts_numbers. The * is the ‘splat’ operator, which means any number of arguments can be passed to the method and they will be ‘splatted’ into an array.</p><p>So if you call a method with parameters like:</p><pre>puts_numbers(&#39;one&#39;, &#39;two&#39;)</pre><p>nums will be an array that looks like:</p><pre>[&#39;one&#39;, &#39;two&#39;]</pre><p>and you will get a string:</p><pre># &quot;num1: one, num2: two&quot;</pre><p>The parameter with the ‘splat’ operator is optional.</p><p>It means that if you don’t pass the arguments to a method, it won’t return an error. For example:</p><pre>puts_numbers()</pre><p>will return:</p><pre>=&gt; nil</pre><p>However, you cannot define a method, that would have 2 parameters with a ‘splat’ operator. If you try to declare and call:</p><pre>def puts_names(*dogs, *cats)<br>    puts dogs<br>    puts cats<br>end</pre><p>you will get a syntax error .</p><p><strong>Double </strong><strong>** operator.</strong></p><p>It’s pretty similar to the original splat operator with one difference: it can be used for hashes. To pass a hash as arguments in Ruby, you need to add ** before your hash. Let’s define a method:</p><pre>def print_data_from_hash(name: &quot;Rose&quot;, age: 1)<br>    [name, age]<br>end</pre><p>name: “Rose”, age: 1 are the default parameters here. We can declare a new hash and use it as a parameter.</p><pre>hash = { name: &#39;Alex&#39;, age: 3 }<br><br>print_data_from_hash(**hash)</pre><p>It will produce:</p><pre># Returns: [&#39;Alex&#39;, 3]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4a6e2d7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serializers in Rails: how to create and use]]></title>
            <link>https://medium.com/@mmmaariieee/serializers-in-rails-how-to-create-and-use-41da4185fbfd?source=rss-2e0da5bf7c87------2</link>
            <guid isPermaLink="false">https://medium.com/p/41da4185fbfd</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Mariia Honcharenko]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 04:14:07 GMT</pubDate>
            <atom:updated>2022-12-05T04:14:07.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Rails API default responses usually have some information, that we don&#39;t need or don&#39;t want to include, for example, create_at or updated_at attributes. For this reason, we can use Active Model Serializers to structure the data we send back to the client.</p><p>First we need to add the gem:</p><pre># Gemfile<br>#...<br>gem &#39;active_model_serializers&#39;</pre><p>Let’s imagine that we have a model Book with a migration like that:</p><pre>class CreateBooks &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :books do |t|<br>      t.string :title<br>      t.integer :year<br>      t.integer :length<br>      t.string :author<br>      t.string :description<br>      t.string :cover_url<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><p>If you set up show action and navigate to localhost:3000/books/1 , you will see:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>  &quot;year&quot;: 1925,<br>  &quot;length&quot;: 208,<br>  &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>  &quot;description&quot;: &quot;Set in Jazz Age New York, the novel tells the tragic story of Jay Gatsby, a self-made millionaire, and his pursuit of Daisy Buchanan, a wealthy young woman whom he loved in his youth.&quot;,<br>  &quot;cover_url&quot;: &quot;https://pisces.bbystatic.com/image2/BestBuy_US/images/products/3071/3071213_so.jpg&quot;,<br>  &quot;created_at&quot;: &quot;2022-11-04T22:27:38.682Z&quot;,<br>  &quot;updated_at&quot;: &quot;2022-11-04T22:27:38.682Z&quot;<br>}</pre><p><strong>How to create serializer</strong></p><p>In order to create a serializer, we need to run:</p><pre>rails g serializer book</pre><p>In your app/serializers/book_serializer you will see next code:</p><pre>class BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id<br>end</pre><p>Now the default structure for Book model will consist of only :id . If you try to make a request to localhost:3000/books/1 , you will see:</p><pre>{<br>  &quot;id&quot;: 1<br>}</pre><p>Only the attributes specified in the list will be sent as a JSON responce, so let’s modify it.</p><pre>class BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :title, :year, :length, :author, :description, :cover_url<br>end</pre><p>Now we can get a response, which looks like:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>  &quot;year&quot;: 1925,<br>  &quot;length&quot;: 208,<br>  &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>  &quot;description&quot;: &quot;Set in Jazz Age New York, the novel tells the tragic story of Jay Gatsby, a self-made millionaire, and his pursuit of Daisy Buchanan, a wealthy young woman whom he loved in his youth.&quot;,<br>  &quot;cover_url&quot;: &quot;https://pisces.bbystatic.com/image2/BestBuy_US/images/products/3071/3071213_so.jpg&quot;<br>}</pre><p><strong>How to create custom attributes</strong></p><p>We can create custom attributes based on the existing ones. Firstly, we need to add the name of the new attribute to the list. Next, we need to define our method.</p><pre>class BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :title, :year, :length, :author, :description, :cover_url, :summary<br><br>  def summary<br>    &quot;#{self.object.title} by #{self.object.author}: #{self.object.description[0..49]}...&quot;<br>  end<br>end</pre><p>If we restart the server and navigate back to localhost:3000/books/1 , we should see our new summary added at the end of the JSON.</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>  &quot;year&quot;: 1925,<br>  &quot;length&quot;: 208,<br>  &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>  &quot;description&quot;: &quot;Set in Jazz Age New York, the novel tells the tragic story of Jay Gatsby, a self-made millionaire, and his pursuit of Daisy Buchanan, a wealthy young woman whom he loved in his youth.&quot;,<br>  &quot;cover_url&quot;: &quot;https://pisces.bbystatic.com/image2/BestBuy_US/images/products/3071/3071213_so.jpg&quot;,<br>  &quot;summary&quot;: &quot;The Great Gatsby by F. Scott Fitzgerald: Set in Jazz Age New York, the novel tells the tra...&quot;<br>}</pre><p><strong>How to include associations</strong></p><p>To get all the necessary information, we still need to send multiple requests to the database (for example, localhost:3000/reviews ). Fortunately, serializer allows us to specify what associations an object has.</p><pre>#book_app/app/serializers/book_serializer.rb<br>class BookSerializer &lt; ActiveModel::Serializer<br>  attributes :id, :title, :year, :length, :author, :description, :cover_url<br>  has_many :reviews<br>end</pre><p>Now, when we request our user information, we get this:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>  &quot;year&quot;: 1925,<br>  &quot;length&quot;: 208,<br>  &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;,<br>  &quot;description&quot;: &quot;Set in Jazz Age New York, the novel tells the tragic story of Jay Gatsby, a self-made millionaire, and his pursuit of Daisy Buchanan, a wealthy young woman whom he loved in his youth.&quot;,<br>  &quot;cover_url&quot;: &quot;https://pisces.bbystatic.com/image2/BestBuy_US/images/products/3071/3071213_so.jpg&quot;,<br>  &quot;summary&quot;: &quot;The Great Gatsby by F. Scott Fitzgerald: Set in Jazz Age New York, the novel tells the tra...&quot;,<br>  &quot;reviews&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;message&quot;: &quot;Message 1&quot;<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;message&quot;: &quot;Message 2&quot;<br>    },<br>    {<br>      &quot;id&quot;: 3,<br>      &quot;message&quot;: &quot;Message 3&quot;<br>    }<br>  ]<br>}</pre><p>(In order to structure the data we send back from the Review model, we can create review_serializer and modify the list of attributes).</p><p>You can reed more about serialization in Ruby on Rails documentation:</p><p><a href="https://api.rubyonrails.org/classes/ActiveModel/Serialization.html">ActiveModel::Serialization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41da4185fbfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>