<?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 Izzy on Medium]]></title>
        <description><![CDATA[Stories by Izzy on Medium]]></description>
        <link>https://medium.com/@izzyo?source=rss-ff3f2976a48d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wb-BGJkG3B6k9MQcPxHH9g@2x.jpeg</url>
            <title>Stories by Izzy on Medium</title>
            <link>https://medium.com/@izzyo?source=rss-ff3f2976a48d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:54:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@izzyo/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[Building Spotify Data Pipeline with Python]]></title>
            <link>https://medium.com/@izzyo/building-spotify-data-pipeline-with-python-ef3afc86cd2a?source=rss-ff3f2976a48d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef3afc86cd2a</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Izzy]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 22:35:06 GMT</pubDate>
            <atom:updated>2023-11-30T22:35:06.588Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3vRlT2k2L35Cnn5C%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdance-donald-l3vRlT2k2L35Cnn5C&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMDhkZDVrYnIxOHIzcGI1aXZhdDZyem5xanF2MTk1a3loOTJoNTE1cSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fl3vRlT2k2L35Cnn5C%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="350" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0bf0398da8d0c079b1ec210fde123e1/href">https://medium.com/media/f0bf0398da8d0c079b1ec210fde123e1/href</a></iframe><p>Let’s start by exploring into the fundamental concept of a data pipeline — an intricate mechanism designed to streamline the flow of information. Specifically, our focus narrows to the creation of a data pipeline tailored for Spotify data.</p><blockquote><strong>Spotify, </strong>with its vast repository of user interactions, presents a wealth of data that, when properly harnessed, can unveil user preferences, trends, and patterns.</blockquote><p>The significance of a well-crafted data pipeline cannot be overstated. It is the bridge that transforms raw data into actionable insights, making it an indispensable tool.By establishing an efficient data pipeline tailored to <a href="https://developer.spotify.com/documentation/web-api"><strong>Spotify’s Web API,</strong></a> we unlock the ability to extract, transform, and store this data systematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OTAig8ekd2iNFy5Y.png" /></figure><p>This blog will dive deep into the fascinating world of building a data pipeline tailored specifically for Spotify. Throughout this journey, we will explore the challenges we encountered, the solutions we discovered, and the valuable insights we gained along the way. So, come along and join us as we unravel the art of constructing an efficient data pipeline for Spotify data.</p><blockquote>Let’s get started!</blockquote><p><strong>Project Overview Steps</strong></p><ol><li><strong>Connect to the Spotify Web API: </strong>I find hard time trying to figure it out how to fetch data from the spotify API . There was none timely done projects to reference to . Go to the <a href="https://developer.spotify.com/dashboard/"><strong><em>Spotify Developer Dashboard</em></strong></a> and log in or create an account if you don’t have one.</li></ol><p>2.<strong> Get Your Client ID and Client Secret: </strong>Once logged in, create a new app to obtain your Client ID and Client Secret.</p><pre>Client ID: xxxxxxxxxxxxxxxxxxxxxxxxx<br>Client secret : xxxxxxxxxxxxxxxxxxxxxxxxx<br>Redirect URIs : https://localhost:3000/callback</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdxTCtnToOFDbEdIoPSy3Q.png" /><figcaption>spotify create app demo</figcaption></figure><p>3. <strong>Choose an Authorization Flow : </strong>Spotify offers various authorization flows. For simplicity, you might start with the “<strong>Authorization Code Flow</strong>.” This involves redirecting the user to a Spotify login page and obtaining an authorization code.</p><p><strong>4. Build simple flask web app :</strong> After importing the necessary libraries and getting the client ID and secret key build simple spotify redirected login web app.</p><pre>from flask import Flask, request, redirect, jsonify<br>.....<br><br>app = Flask(__name__)<br><br>client_id = os.getenv(&#39;SPOTIFY_CLIENT_ID&#39;)<br>client_secret = os.getenv(&#39;SPOTIFY_CLIENT_SECRET&#39;)<br><br>redirect_uri = &#39;http://localhost:3000/callback&#39;<br><br>def generate_random_string(length):<br>    &quot;&quot;&quot;<br>    Generates a random string of the specified length. <br>    This function is typically used to create a unique &#39;state&#39; parameter <br>    during the OAuth 2.0 authorization process to prevent cross-site request forgery (CSRF) attacks.<br>    <br>    Parameters:<br>    - length (int): The length of the random string to generate.<br>    <br>    Returns:<br>    - str: A randomly generated string.<br>    &quot;&quot;&quot;<br>    rand_Str = string.ascii_letters + string.digits<br>    return &#39;&#39;.join(random.choice(rand_Str) for _ in range(length))</pre><blockquote><strong>What are scopes ?</strong></blockquote><p>Scopes provide Spotify users using third-party apps the confidence that only the information they choose to share will be shared. Scopes are needed when implementing some of the authorization grant types.</p><p>For example , you want to fetch recently played tracks for this type of operation you need to authorize the app to access user-read-recently-played scope.</p><p><strong>ENDPOINT : </strong><a href="https://api.spotify.com/v1/me/player/currently-playing">https://api.spotify.com/v1/me/player/currently-playing</a></p><pre>@app.route(&#39;/login&#39;)<br>def login():<br>    state = generate_random_string(16)<br>    scope = &#39;user-read-private user-read-email user-read-recently-played playlist-read-private playlist-read-private user-top-read user-library-read user-follow-read&#39;<br>    params = {<br>        &#39;response_type&#39;: &#39;code&#39;,<br>        &#39;client_id&#39;: client_id,<br>        &#39;scope&#39;: scope,<br>        &#39;redirect_uri&#39;: redirect_uri,<br>        &#39;state&#39;: state<br>    }<br>    redirect_url = &#39;https://accounts.spotify.com/authorize?&#39; + urllib.parse.urlencode(params)<br>    return redirect(redirect_url)<br><br></pre><p><strong>Obtain an Access Token</strong></p><p>Exchange the authorization code for an access token using the /api/token endpoint. This token will be used to authenticate your requests to the Spotify API.</p><pre>@app.route(&#39;/callback&#39;)<br>def callback():<br>    code = request.args.get(&#39;code&#39;, None)<br>    state = request.args.get(&#39;state&#39;, None)<br><br>    if state is None:<br>        return jsonify({&#39;error&#39;: &#39;state_mismatch&#39;}), 400<br>    else:<br>        auth_options = {<br>            &#39;url&#39;: &#39;https://accounts.spotify.com/api/token&#39;,<br>            &#39;data&#39;: {<br>                &#39;code&#39;: code,<br>                &#39;redirect_uri&#39;: redirect_uri,<br>                &#39;grant_type&#39;: &#39;authorization_code&#39;<br>            },<br>            &#39;headers&#39;: {<br>                &#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>                &#39;Authorization&#39;: &#39;Basic &#39; + base64.b64encode(f&#39;{client_id}:{client_secret}&#39;.encode(&#39;utf-8&#39;)).decode(&#39;utf-8&#39;)<br>            }<br>        }<br><br>        response = requests.post(auth_options[&#39;url&#39;], data=auth_options[&#39;data&#39;], headers=auth_options[&#39;headers&#39;])<br>        token_info = response.json()<br>        <br>        # Store the token_info for further analysis<br>        with open(&#39;token_info.json&#39;, &#39;w&#39;) as json_file:<br>            json_file.write(json.dumps(token_info, indent=4))<br>        <br>        # Return a response<br>        return jsonify({&#39;message&#39;: &#39;Authentication successful&#39;})</pre><blockquote><strong><em>After successfully logged in the token info will be stored in a json file.</em></strong></blockquote><p><strong>Refreshing tokens</strong></p><p>This part was the trickiest one because a<a href="https://developer.spotify.com/documentation/web-api/concepts/access-token">ccess tokens</a> are intentionally configured to have a limited lifespan (<strong>1 hour</strong>), at the end of which, new tokens can be obtained by providing the original refresh token acquired during the authorization token request.</p><pre>{<br>   &quot;access_token&quot;: &quot;NgCXRK...MzYjw&quot;,<br>   &quot;token_type&quot;: &quot;Bearer&quot;,<br>   &quot;scope&quot;: &quot;user-read-private user-read-email&quot;,<br>   &quot;expires_in&quot;: 3600,<br>   &quot;refresh_token&quot;: &quot;NgAagA...Um_SHo&quot;<br>}</pre><p>We need to refresh the access_token by using the refresh_token response key.</p><p>To refresh an access token, we must send a POST request with the grant_type of refresh_token<strong> and </strong>Content-Type of application/x-www-form-urlencoded.</p><pre>@app.route(&#39;/refresh_token&#39;)<br>def refresh_token():<br>    refresh_token = request.args.get(&#39;refresh_token&#39;, None)<br><br>    if refresh_token is None:<br>        return jsonify({&#39;error&#39;: &#39;missing_refresh_token&#39;}), 400<br><br>    auth_options = {<br>        &#39;url&#39;: &#39;https://accounts.spotify.com/api/token&#39;,<br>        &#39;data&#39;: {<br>            &#39;grant_type&#39;: &#39;refresh_token&#39;,<br>            &#39;refresh_token&#39;: refresh_token<br>        },<br>        &#39;headers&#39;: {<br>            &#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>            &#39;Authorization&#39;: &#39;Basic &#39; + base64.b64encode(f&#39;{client_id}:{client_secret}&#39;.encode(&#39;utf-8&#39;)).decode(&#39;utf-8&#39;)<br>        }<br>    }<br><br>    response = requests.post(auth_options[&#39;url&#39;], data=auth_options[&#39;data&#39;], headers=auth_options[&#39;headers&#39;])<br>    token_info = response.json()<br>    # Write the modified token_info back to the file<br>    with open(&#39;token_info_refreshed.json&#39;, &#39;w&#39;) as json_file:<br>        json.dump(token_info, json_file, indent=4)<br>        <br>    # Load existing token_info from the file<br>    with open(&#39;token_info.json&#39;, &#39;r&#39;) as json_file:<br>        token_info = json.load(json_file)<br><br>    # Load refreshed token_info from the file<br>    with open(&#39;token_info_refreshed.json&#39;, &#39;r&#39;) as refreshed_json_file:<br>        refreshed_token_info = json.load(refreshed_json_file)<br><br>    # Update the original token_info with the refreshed access_token<br>    token_info[&#39;access_token&#39;] = refreshed_token_info[&#39;access_token&#39;]<br><br>    # Write the modified token_info back to the file<br>    with open(&#39;token_info.json&#39;, &#39;w&#39;) as json_file:<br>        json.dump(token_info, json_file, indent=4)<br>        <br>    return jsonify({&#39;message&#39;: &#39;Token have been successfully refreshed&#39;})</pre><p><strong>Now we have successfully refreshed the access token !!</strong></p><pre>if __name__ == &#39;__main__&#39;:<br>    app.run(port=3000)</pre><p>Save the above code and run the flask app by using this command</p><pre>python3 spotify_flask_app.py</pre><p>It will redirect to <a href="https://localhost:3000/"><strong>https://localhost:3000</strong></a>. Then we are going to login by adding <strong><em>/login</em></strong> . After successfully logged in , try simulating to expire the access_token by setting the <em>“expires_in”</em>: 3600 to any new value .</p><pre>   &quot;expires_in&quot;: 120 // It will expire in two minutes</pre><p>5. <strong>Make API Request</strong></p><p>For this part I have used <strong>Jupiter notebook</strong> for data cleaning and transformation .</p><p>Now that you have the access token, we can start making requests to the Spotify API. For example, we can use the /v1/me endpoint to get information about the authenticated user.</p><pre># Read token_info data from the JSON file<br>with open(&#39;./token_info.json&#39;, &#39;r&#39;) as json_file:<br>    token_info = json.load(json_file)<br><br>token = token_info[&#39;access_token&#39;]<br>headers =  &#39;&#39;</pre><p><strong>I have used logger to log the overall process and to check from it.</strong></p><pre># Set up logging<br>import logging as logger<br>...<br><br>logger.basicConfig(filename=&#39;spotify_api.log&#39;, level=logger.DEBUG)</pre><p>Now we can proceed to fetch from the API.</p><pre>def fetch_web_api(endpoint, method=&#39;GET&#39;, body=None):<br>    headers = {&#39;Authorization&#39;: f&#39;Bearer {token}&#39;}<br>    url = f&#39;https://api.spotify.com/{endpoint}&#39;<br>    <br>    # Log the request information<br>    logger.debug(f&quot;Sending {method} request to {url} with headers {headers} and body {body}&quot;)<br><br>    response = requests.request(method, url, headers=headers, json=body)<br>    <br>    # Log the response information<br>    logger.debug(f&quot;Received response with status code {response.status_code} and content {response.text}&quot;)<br><br>    # print(response.json())<br>    return response.json()</pre><p>In this project we are using <strong><em>recently-played</em></strong> endpoint .</p><pre>def recently_played():<br>try:<br>    endpoint = &#39;v1/me/player/recently-played?after={time}&amp;limit=50&#39;.format(time=yesterday_date_ux, headers=headers)<br>    return fetch_web_api(endpoint)<br>    <br>except Exception as e:<br>    logger.error(f&quot;Error while fetching recently played tracks: {e}&quot;)<br>    return None<br><br>recently_played_tracks = recently_played()</pre><p>Let’s see the data first and we sill store it in a dictionary.</p><pre>if &#39;items&#39; in recently_played_tracks:<br>    for track in recently_played_tracks[&#39;items&#39;]:<br>        artists_name = [artist[&#39;name&#39;] for artist in track[&#39;track&#39;][&#39;artists&#39;]]<br>        artists_names = &#39;, &#39;.join(artists_name)<br>        song_name = track[&#39;track&#39;][&#39;album&#39;][&#39;name&#39;]<br>        # Extract the first 19 characters to get the datetime string<br>        played_at_time = track[&#39;played_at&#39;][:19]<br>        # Convert UTC to local time (UTC+3)<br>        played_local_time = convert_utc_to_local(played_at_time, &#39;Etc/GMT-3&#39;)<br>        # Format the datetime without timezone offset<br>        played_local_time = played_local_time.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>        print(f&quot;{song_name} by &quot;<br>              f&quot;{artists_names} played at  &quot;<br>              f&quot;{played_local_time}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-_flPKvMPMiOcEhU6z4WQ.png" /><figcaption>recently played tracks after 5 days before</figcaption></figure><pre>song_names = []<br>artist_names = []<br>played_at_list = []<br>if &#39;items&#39; in recently_played_tracks:<br>    for track in recently_played_tracks[&#39;items&#39;]:<br>        # print(track)<br>        artist_names.append(track[&#39;track&#39;][&#39;artists&#39;][0][&#39;name&#39;])<br>        song_names.append(track[&#39;track&#39;][&#39;album&#39;][&#39;name&#39;])<br>        played_at_time = track[&#39;played_at&#39;][:19]<br>        # Convert UTC to local time (UTC+3)<br>        played_local_time = convert_utc_to_local(played_at_time, &#39;Etc/GMT-3&#39;)<br>        # Format the datetime without timezone offset<br>        played_local_time = played_local_time.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)        <br>        played_at_list.append(played_local_time)<br><br>song_dict = {<br>            &quot;song_name&quot; : song_names,<br>            &quot;artist_name&quot;: artist_names,<br>            &quot;played_at&quot; : played_at_list,<br>}</pre><p>Now we can store it into a panda dataframe.</p><pre>songs_df = pd.DataFrame(song_dict, columns=[&quot;song_name&quot;, &quot;artist_name&quot;,&quot;played_at&quot;])<br>.<br>.<br>.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*ltOE0p9yIHVlVfToDpbHng.png" /></figure><p>I want to know which tracks i was repeatedly playing , based on this data we can recommend tracks (… another project idea…).</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb<br>%matplotlib inline<br>base_color = sb.color_palette()[0]<br>plt.figure(figsize=[10,5])<br>sb.barplot(x=songs_df.values, y = songs_df.index, color=base_color);<br>plt.ylabel(&#39;Song Name&#39;);<br>plt.xlabel(&#39;Times Played&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zv7Md0ZDGkW7Tn8LAs_Mlg.png" /></figure><p>6. <strong>Store the ETL data into MongoDB Database</strong></p><p><a href="https://notebooks.githubusercontent.com/view/%3C/p%3Ehttps://pymongo.readthedocs.io/en/stable/examples/authentication.html">PyMongo : </a>PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python. This documentation attempts to explain everything you need to know to use PyMongo.</p><pre>from pymongo import MongoClient<br><br># Retrieve MongoDB connection string from environment variable<br>mongodb_connection_string = os.getenv(&#39;MONGODB_CONNECTION_STRING&#39;)<br>client = MongoClient(mongodb_connection_string)</pre><pre>client.list_database_names()</pre><p>Check the connection is working by listing the databases.</p><pre>db = client.employees <br>db</pre><blockquote>Database(MongoClient(host=[‘127.0.0.1:27017’], document_class=dict, tz_aware=False, connect=True), ‘employees’)</blockquote><p>Create new collection to store the spotify data</p><pre>collection = db.spotify_songs</pre><p><strong>db.spotify_songs.insert_many(songs_df.to_dict(‘records’))</strong></p><p>This will populate our new collection called spotify_songs on employees sample database .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*VRXJYuGH8DC7C995O9CfZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*YuiVwvKmTB8AHL1brlC3sA.png" /></figure><h3>Conclusion:</h3><p>We started by checking out Spotify’s treasure using their Web API. Imagine it as our way of peeking into Spotify’s massive song collection. We extract the data , transform it using python .The, we load/stored our organized data in MongoDB. We stored it in ‘spotify_songs’ collection to keep our recently played Spotify tracks in one spot.</p><p>Next : Now, we’ve got our manual system working smoothly. But guess what? I am planning to automate the whole thing using <strong>Apache Airflow.</strong></p><p>You can look <a href="https://developer.spotify.com/documentation/web-api">here</a> to discover more about the spotify data and feel free to access all the code on my <a href="https://github.com/codeXXripper/Spotify--Data-Pipeline/tree/main"><strong>GitHub</strong></a> repository.</p><p>Let’s be friends <a href="https://www.linkedin.com/in/israel-fitsum/"><strong>LinkedIn</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef3afc86cd2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2: Leetcode | 72. Edit Distance]]></title>
            <link>https://medium.com/@izzyo/day-2-leetcode-72-edit-distance-c12ac4e75143?source=rss-ff3f2976a48d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12ac4e75143</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Izzy]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 22:19:33 GMT</pubDate>
            <atom:updated>2023-02-26T22:54:11.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Difficulty: Hard Language: JavaScript</p><h3>Background and History</h3><p>The edit distance algorithm is widely used by data scientists and is the basic algorithm used as the evaluation standard for machine translation and speech recognition.</p><p>The edit distance of strings, also known as Levenshtein distance, was proposed by Russian mathematician Vladimir Levenshtein in 1965. Refers to the minimum number of operands required to convert a string A into a string B using character operations.</p><h3>Problem Description</h3><p>Given two strings word1 and word2, return <em>the minimum number of operations required to convert </em><em>word1 to </em><em>word2</em>.</p><p>You have the following three operations permitted on a word:</p><ul><li>Insert a character</li><li>Delete a character</li><li>Replace a character</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*S4ECaVlPlf2_3F9D_dNXng.png" /></figure><h3>Solution</h3><p>The smaller the edit distance of two strings, the more similar they are .If two strings are equal, their edit distance is 0.</p><p>Set two pointers i and j for word1 and word2 respectively, traverse the two strings respectively, and only perform the following three operations during the traversal process:</p><ul><li>Insert a character</li><li>Delete a character</li><li>Replace a character: skip if the characters of the two string comparisons are the same</li></ul><p><strong>matrix[i][j]</strong> indicates the edit distance between the word1 starting from the 0th character to the i-th character and the word2 starting from the 0th character to the j-th character.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*c6O38BXZP23W9diW66DxiA.png" /></figure><p><strong>This solution works great!</strong></p><p>Source Code :) <a href="https://github.com/codeXXripper/Leetcode-JS">https://github.com/codeXXripper/Leetcode-JS</a></p><blockquote><strong><em>Follow me for more</em></strong></blockquote><blockquote><a href="https://www.linkedin.com/in/israel-fitsum/"><strong>https://www.linkedin.com/in/israel-fitsum/</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12ac4e75143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 1: Leetcode | 121. Best Time To Buy And Sell Stock Solution]]></title>
            <link>https://medium.com/@izzyo/day-1-leetcode-121-best-time-to-buy-and-sell-stock-c550af3dc481?source=rss-ff3f2976a48d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c550af3dc481</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Izzy]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 22:17:28 GMT</pubDate>
            <atom:updated>2023-02-26T22:52:52.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Difficulty: Easy Language: JavaScript</p><h3>Problem Description</h3><p>You have given an array prices where prices[i] is the price of a given stock<br>on the ith day.</p><p>You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.</p><p>Return the maximum profit you can achieve from this transaction.<br>If you cannot achieve any profit, return 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*US0H13lrIQoX_TTkJAwV8w.png" /></figure><p>Explanation 1: Buy on day 2 (price = 1) andsell on day 5 (price = 6), profit = 6–1 = 5. Not 7–1 = 6, as selling price needs to be larger than buying price.</p><p><strong>Note that buying on day 2 and selling on day 1 is not allowed<br>because you must buy before you sell.</strong></p><p>Explanation 2 : In this case, no transactions are done and the max profit =0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*h5fltuvpJGL0O-3nOiL8Ng.png" /></figure><h4>Brute Force Solution — O(n²)</h4><p>To solve this problem, first, we use a <strong>Brute force algorithm approach</strong>. we will try all possible profits we can get from the given values and pick the highest one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*YDJOw4H7eplnCSH-oB6GYw.png" /></figure><blockquote><strong>Failed time complexity : O(n²)<br>Input size is 10⁵, so that the nested loop will cause TLE(time limit exceed).</strong></blockquote><h4>Better Solution — O(n)</h4><p>We can go through all of the prices and we can instead keep track of the minimum price and subtract it from the selling prices like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*0al1-AIGmpyCLyUYkk8vvw.png" /></figure><h4><strong>Complexity analysis</strong></h4><blockquote><strong>Time complexity: O(n) </strong><br><strong>Space complexity: O(1)</strong></blockquote><p><strong>This solution works great!</strong></p><p>Source Code :) <a href="https://github.com/codeXXripper/Leetcode-JS">https://github.com/codeXXripper/Leetcode-JS</a></p><blockquote><strong><em>Follow me for more</em></strong></blockquote><blockquote><a href="https://www.linkedin.com/in/israel-fitsum/"><strong><em>https://www.linkedin.com/in/israel-fitsum/</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c550af3dc481" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>