<?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 Bogdan Tudorache on Medium]]></title>
        <description><![CDATA[Stories by Bogdan Tudorache on Medium]]></description>
        <link>https://medium.com/@tudorache.a.bogdan?source=rss-d32fc2c46868------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*saaIgYzW1z0UjtXcBLcXhg.jpeg</url>
            <title>Stories by Bogdan Tudorache on Medium</title>
            <link>https://medium.com/@tudorache.a.bogdan?source=rss-d32fc2c46868------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:50:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tudorache.a.bogdan/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[Privacy isn’t a feature, it’s an obligation]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/privacy-isnt-a-feature-it-s-an-obligation-3578cd81d3f9?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/3578cd81d3f9</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-app-security]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 22:19:30 GMT</pubDate>
            <atom:updated>2026-03-13T22:28:10.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building trustworthy applications through security by design</h3><p>Most applications that handle your personal data don’t encrypt it.</p><p>They store it in plaintext on third-party servers. They send it through public APIs to train machine learning models. They back it up to cloud services owned by companies you’ve never heard of.</p><p>Then they call it “privacy.”</p><p>They’ll add a privacy policy. They’ll mention encryption in their marketing. They’ll promise not to sell your data (while still feeding it to third-party AI companies). And they’ll sleep fine at night because they technically followed the letter of the law.</p><p>But here’s what nobody says out loud: if you’re building a tool that stores personal details about someone’s relationships — their health struggles, their family situations, their career anxieties, their confidential professional contacts — you have an obligation. Not a feature. An obligation.</p><p>The obligation to make sure that data never leaves your control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qWiibvAt6yEZWrgJkHOJQg.png" /></figure><p>We started building Meaningful around this principle. And it forced us to rethink everything about how modern applications are built. More importantly, it forced us to rethink <em>how we write secure code</em>.</p><h3>The problem with “privacy as a feature”</h3><p>When privacy is treated as a feature, it becomes optional.</p><p>It’s something you add because users ask for it. Something you charge money for. Something you mention in the landing page copy and then move on.</p><p>But privacy for relationship data isn’t optional. It’s fundamental.</p><p>Consider what happens when you log a note about your friend: “struggling with depression, mentioned it over coffee.” That’s not metadata. That’s not an email. That’s someone’s private life. If that leaks, it doesn’t just expose data. It violates trust.</p><p>Or what happens when you record a voice note after talking to a colleague: “internally frustrated with management, looking for exit opportunities.” That’s career-sensitive information. In the wrong hands, it ends someone’s opportunities.</p><p>Most relationship management tools don’t think about this at all. They treat relationship data the same way they treat any other user data: convenient to store, easy to monetize, useful for training models.</p><p>The problem is relationship data is <em>different</em>.</p><p>It’s not your data alone. It’s other people’s personal life. Their most precious memories. Things they told you in confidence that you’re just keeping a note about.</p><h3>What goes wrong when relationship data leaks</h3><p>It’s not hypothetical.</p><p>In 2021, a misconfigured S3 bucket leaked millions of contact records from a major CRM platform. Not just names and phone numbers. Notes. Conversation history. Personal details.</p><p>In 2023, an AI training dataset included relationship management tool exports — full chat histories, personal notes, everything. People’s private thoughts about their friends and colleagues became training data for a language model.</p><p>It doesn’t have to be a headline breach. Sometimes it’s just negligence.</p><p>A developer leaves a MongoDB connection string with authentication disabled. A backup gets stored in the wrong region. A third-party API integration gets compromised. A disgruntled employee exports user data.</p><p>And suddenly, everything you recorded about your relationships is out there.</p><p>But here’s what’s worse: you probably didn’t even know it was vulnerable. Because the tool you trusted with that data didn’t encrypt it. They just promised to “keep it safe.” Which is like promising to keep your house safe by having the front door unlocked but hoping no one walks in.</p><h3>Why third-party AI is a privacy nightmare</h3><p>Most “AI features” in relationship tools are actually just API calls to OpenAI or Anthropic.</p><p>Your relationship data gets sent to their servers. They process it. They return a response. And somewhere in the terms of service, it says they might use your data to improve their models.</p><p>The companies doing this aren’t being malicious. They’re following their business model. But the business model is: <em>user data is a training asset</em>.</p><p>So when you ask your personal CRM “who haven’t I talked to in 3 months?” you’re not just getting an answer. You’re sending your entire contact list, interaction history, and relationship context to a third-party server. Where it gets logged. Cached. Possibly included in training data.</p><p>This is especially problematic for relationship data because it reveals patterns about your actual life. Your friends. Your family. Your professional network. Your vulnerabilities.</p><p>An AI trained on millions of people’s relationship data can infer things about you that you never explicitly said. It can infer who your best friends are. Who your romantic interests might be. Who’s struggling. Who’s isolated.</p><p>That’s not data you consented to share. And definitely not data you should have to share to use a relationship management tool.</p><h3>How we built Meaningful differently</h3><p>When we started building Meaningful, we made a different choice.</p><p>We decided: relationship data stays in your control. Full stop.</p><p>That meant several technical decisions that complicate our infrastructure but protect your privacy. And it meant establishing a security-first development process to ensure we never accidentally compromise that promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGVAKQ1Y6llf1Fdjt4zsXw.png" /></figure><h3>Encryption at rest with per-user keys and salts</h3><p>All personal data — your contacts, your notes, your interaction history, anything sensitive — gets encrypted with AES-256-CTR before it touches our MongoDB database.</p><p>But here’s the part that matters: <strong>we don’t use a single master key for all users</strong>.</p><p>Each user gets a unique encryption salt stored in their account. When we encrypt their data, we derive a unique key for that user using:</p><pre>userKey = HMAC-SHA256(ENCRYPTION_KEY, userId + encryptionSalt)</pre><p>This means:</p><ul><li>If our database is compromised, attackers get encrypted data</li><li>Even if the master encryption key is leaked, they’d need 400+ individual user salts to decrypt anything</li><li>Each user’s data is isolated — a breach doesn’t expose everyone</li></ul><p>Each piece of encrypted data stores a random 16-byte initialization vector (IV) and the ciphertext. On read, we decrypt server-side and strip the ciphertext before sending anything to your browser. You never see the encrypted version. But the database only stores the encrypted version.</p><p>This means if someone breaks into our database, they get ciphertext. Not your actual data.</p><h3>Private AI inference (no third-party APIs)</h3><p>Our AI assistant, EdgeAI, runs on a dedicated DigitalOcean droplet that we control. Not OpenAI. Not Anthropic. Not any third-party API.</p><p>The model is Llama 3.2 3B, open-source and quantized to run on modest hardware (4GB RAM, 2 vCPUs). It processes your requests locally. Your data never leaves our infrastructure.</p><p>When you ask EdgeAI “who should I reconnect with?” your contact list, interaction history, and journal entries stay on our servers. The model reads them. Produces a response. And that’s it. No logs sent to third parties. No training data harvested.</p><p>The trade-off is infrastructure cost and complexity. We pay for a dedicated droplet. We manage model updates ourselves. We own the responsibility if something breaks.</p><p>But the benefit is: your relationship data is never exposed to third-party training pipelines.</p><h3>Local transcription for voice notes</h3><p>We use faster-whisper (OpenAI’s open-source Whisper model) running locally to transcribe voice notes.</p><p>You record a note. It gets transcribed on your device or on our servers — but the audio never touches OpenAI. It stays local.</p><p>This matters because audio contains not just what you said, but tone, emotion, context. It’s rich data about your relationships. Sending it to third parties for transcription would leak that.</p><h3>Selective encryption based on context</h3><p>We don’t encrypt everything equally because not everything is equally sensitive.</p><p>A chat message where you ask EdgeAI “how do I politely decline an event?” gets encrypted because it might involve relationship context.</p><p>A chat message where you ask “what’s the capital of France?” doesn’t get encrypted because it’s not personal data.</p><p>The decision is made at write time based on the intent of the conversation. App-query and app-action intents (anything touching your actual contacts and relationships) get encrypted. General knowledge and chitchat don’t.</p><p>This is a tradeoff: encrypted data can’t be cached or quickly searched across users. But it’s the right tradeoff for relationship data.</p><h3>Building a security-first development strategy</h3><p>Here’s what sets security apart from other technical choices: you can refactor a bad architecture. You can rewrite inefficient code. But you can’t “fix” a security breach after the fact.</p><p>We take security seriously. And we don’t share your data with anyone because we know how important it is for you.</p><p>That means security isn’t something we patch in at the end. It’s woven into how we think about every feature, every API, every line of code that touches your data.</p><p>Writing secure code isn’t about writing it once and hoping it works. It’s about building security reviews into your development process.</p><p>We didn’t want to just implement encryption. We wanted to make sure the implementation was actually solid. So we built a systematic security review workflow.</p><h3>Starting with the security-reviewer skill</h3><p>We started by adapting the <a href="https://github.com/affaan-m/everything-claude-code/blob/fdea3085a76c842edea49a72ea695ccc7ff537ed/agents/security-reviewer.md">security-reviewer skill</a> from the Claude Code community. This skill provides a comprehensive framework for detecting OWASP Top 10 vulnerabilities, hardcoded secrets, injection attacks, and unsafe cryptographic practices.</p><p>But we realized a general-purpose security reviewer wasn’t enough for our specific needs. We needed custom security reviews for the three areas that matter most for Meaningful: encryption, authentication, and input validation.</p><h3>Building three custom security skills</h3><p>We created three specialized security review skills tailored to our codebase:</p><p><strong>1. </strong><a href="https://meaningful-space-bucket.ams3.digitaloceanspaces.com/BlogMedia/skills/security/security-review-encryption.md"><strong>security-review-encryption.md</strong></a></p><p>This skill checks:</p><ul><li>No hardcoded encryption keys (always in process.env)</li><li>Salt generation uses crypto.randomBytes() (not predictable)</li><li>Key derivation uses HMAC-SHA256 (strong hash)</li><li>No plaintext data logged after encryption</li><li>Version field prevents algorithm downgrades (old data stays readable)</li></ul><p><strong>2. </strong><a href="https://meaningful-space-bucket.ams3.digitaloceanspaces.com/BlogMedia/skills/security/security-review-auth.md"><strong>security-review-auth.md</strong></a></p><p>This skill checks:</p><ul><li>All sensitive routes have auth middleware</li><li>Passwords hashed with bcrypt (never plaintext comparison)</li><li>JWT tokens validated on every request</li><li>No hardcoded secrets</li><li>Role-based access control enforced</li></ul><p><strong>3. </strong><a href="https://meaningful-space-bucket.ams3.digitaloceanspaces.com/BlogMedia/skills/security/security-review-input.md"><strong>security-review-input.md</strong></a></p><p>This skill checks:</p><ul><li>All user inputs validated (type, length, pattern)</li><li>No SQL injection (using parameterized queries)</li><li>No XSS (React auto-escapes, but we verify)</li><li>File uploads have size and type limits</li><li>API responses filtered (passwords/secrets never returned)</li></ul><h3>Core security checks we run</h3><p>For every code change touching encryption, auth, or user input, we run these checks:</p><pre># 1. Check for hardcoded secrets<br>grep -r &quot;ENCRYPTION_KEY\|API_KEY\|SECRET&quot; server/ \<br>  --include=&quot;*.js&quot; | grep -v &quot;process.env&quot; | grep -v &quot;.env&quot;</pre><pre># 2. Check for SQL injection patterns<br>grep -r &quot;query.*req\.body\|query.*req\.query&quot; server/ --include=&quot;*.js&quot;</pre><pre># 3. Check for plaintext password comparison<br>grep -r &quot;password\s*==&quot; server/ --include=&quot;*.js&quot;</pre><pre># 4. Check for unprotected routes<br>grep -r &quot;router\.\(post\|put\|delete\)&quot; server/routes --include=&quot;*.js&quot; \<br>  | grep -v &quot;auth&quot; | grep -v &quot;public&quot;</pre><pre># 5. Run npm audit<br>npm audit --audit-level=high</pre><pre># 6. Check encryption key derivation<br>grep -r &quot;deriveUserKey\|HMAC\|hmac&quot; server/utils/encryption.js</pre><h3>Quick security audit script</h3><p>We also use a quick shell script that developers can run before committing:</p><pre>#!/bin/bash<br>echo &quot;🔐 Security Audit — Meaningful&quot;<br>echo &quot;================================&quot;</pre><pre>echo &quot;1. Checking for hardcoded secrets...&quot;<br>grep -r &quot;ENCRYPTION_KEY\|API_KEY\|SECRET\|password&quot; server/ \<br>  --include=&quot;*.js&quot; | grep -v &quot;process.env&quot; | grep -v &quot;.env&quot; || echo &quot;✅ No secrets found&quot;</pre><pre>echo -e &quot;\n2. Checking npm dependencies...&quot;<br>npm audit --audit-level=high || echo &quot;⚠️ Some vulnerabilities found&quot;</pre><pre>echo -e &quot;\n3. Checking for unprotected routes...&quot;<br>grep -r &quot;router\.\(post\|put\|delete\)&quot; server/routes --include=&quot;*.js&quot; \<br>  | grep -v &quot;, auth&quot; | grep -v &quot;public&quot; || echo &quot;✅ All sensitive routes protected&quot;</pre><pre>echo -e &quot;\n4. Checking encryption usage...&quot;<br>grep -r &quot;encrypt\|decrypt&quot; server/routes --include=&quot;*.js&quot; \<br>  | grep -v &quot;encryptionSalt&quot; | head -5</pre><pre>echo -e &quot;\n✅ Audit complete. Review findings above.&quot;</pre><p>This is the kind of thing that’s boring to do manually but trivial to automate. By running it every time code touches security-sensitive areas, we catch problems early.</p><h3>The infrastructure cost of privacy</h3><p>Being privacy-first is expensive.</p><p>We run a second server just for AI inference. We manage encryption keys and rotation ourselves. We store more data (encrypted data is larger than plaintext). We can’t use certain optimization techniques that would require plaintext access.</p><p>If we were comfortable with the standard playbook — send everything to OpenAI, store data plaintext, train on user interactions — we could save significant costs.</p><p>But we’re not.</p><p>Because relationship data isn’t a cost center to optimize. It’s something we’re responsible for protecting.</p><h3>What this means for you</h3><p>When you use Meaningful, here’s what’s actually happening:</p><ol><li>Your contact information and relationship notes get encrypted with AES-256 using a key derived from your account</li><li>Your voice notes get transcribed locally</li><li>Your AI assistant processes everything on a private server</li><li>Your calendar sync stays within your control</li><li>Your data is never sent to third-party AI APIs for training</li><li>We run security audits before every code change touching encryption, auth, or user input</li></ol><p>This doesn’t make Meaningful immune to data breaches. No system is. But it means if something does go wrong, the damage is limited to encrypted data. And we have a very high responsibility to protect it because we control it entirely.</p><p>It also means EdgeAI won’t hallucinate as easily. Instead of sending sparse context to a 70B parameter model trained on the entire internet, we send rich, relevant context to a small model running on our infrastructure. The model stays grounded in your actual relationship data instead of making things up based on general knowledge.</p><h3>The philosophy behind this</h3><p>This isn’t about being preachy about privacy.</p><p>It’s about recognizing what relationship data actually is: someone’s trust, written down.</p><p>And it’s about recognizing that security is something you build into every decision, not something you bolt on at the end. It’s not a feature. It’s an obligation.</p><p>If you’re building an application that touches people’s personal information, you need to ask yourself: are we treating security like a feature we’ll add later? Or are we building it into the foundation?</p><p>The difference matters. And your users will notice.</p><h3>Resources</h3><p>If you’re building privacy-focused applications, you might find these resources useful:</p><ul><li><a href="https://github.com/affaan-m/everything-claude-code">Security-reviewer skill</a> — The foundational repository for claude code from where framework we adapted</li><li>Meaningful security skills — Our three custom security review skills (encryption, auth, input validation)</li><li><a href="https://owasp.org/www-project-top-ten/">OWASP Top 10</a> — Essential reference for web application security</li></ul><p>Try <a href="https://someaningful.com/">Meaningful</a> — fully free during alpha.</p><p>The code is built on security. The commitment to your privacy is real.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3578cd81d3f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEO best practices for modern web apps]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/seo-best-practices-for-modern-web-apps-b0ba8bde1331?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ba8bde1331</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[seo-tips]]></category>
            <category><![CDATA[server-side-injection]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 21:31:01 GMT</pubDate>
            <atom:updated>2026-03-03T21:31:01.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>server-side meta injection without the headache</h3><p>You build a beautiful React app. Fast. Responsive. Users love it.</p><p>Then you check Google Search Console and realize: <strong>search engines see nothing</strong>.</p><p>Empty pages. No titles. No descriptions. Just a blank &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;.</p><p>This is the single-page application (SPA) SEO problem. And it’s costing you traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOb38-fEQHMO3EXvTkhcig.jpeg" /></figure><h3>Why traditional solutions fail</h3><p>Most developers reach for one of these:</p><p><strong>Prerendering with Puppeteer</strong> — Spins up a headless browser, renders your app, saves HTML. Sounds great until you realize it’s slow, memory-hungry, and breaks in production because you forgot to install Chromium in your Docker container.</p><p><strong>Next.js or other SSR frameworks</strong> — Powerful, but requires rewriting your entire app. Not an option when you’re already in production.</p><p><strong>React Helmet alone</strong> — Works client-side, but crawlers don’t always execute JavaScript. You’re gambling with your SEO.</p><p>We tried all of these. They all failed in different ways.</p><h3>The solution: server-side meta injection</h3><p>Here’s what actually works: <strong>inject SEO meta tags at the server level</strong> before sending HTML to the client.</p><p>No Puppeteer. No framework migration. Just clean, reliable SEO.</p><p><strong>How it works:</strong></p><ol><li>Build your React app as normal</li><li>Server intercepts requests for public routes</li><li>Injects meta tags into the HTML before sending response</li><li>Crawlers see everything — title, description, canonical, Open Graph, schema markup</li></ol><p>The entire implementation is ~500 lines of code.</p><h3>Implementation</h3><p><strong>Step 1: Create your meta map</strong></p><p>Define all your routes and their SEO metadata in one place:</p><pre>// server/seoMeta.js<br>const BASE_URL = &#39;https://someaningful.com&#39;;<br>const OG_IMAGE = &#39;https://someaningful.com/og-image.png&#39;;</pre><pre>const STATIC_META = {<br>  &#39;/&#39;: {<br>    title: &#39;Meaningful | Personal CRM &amp; Contact Manager&#39;,<br>    description: &#39;Organize your contacts, track interactions, and stay connected with a private AI assistant. Free during Alpha.&#39;,<br>    ogTitle: &#39;Meaningful | Personal CRM &amp; Contact Manager&#39;,<br>    ogDescription: &#39;The personal relationship manager built for individuals.&#39;,<br>    canonical: `${BASE_URL}/`,<br>    robots: &#39;index, follow&#39;,<br>  },<br>  &#39;/features&#39;: {<br>    title: &#39;Features | Meaningful Personal CRM&#39;,<br>    description: &#39;Contact management with AI assistant, voice notes, network visualization, and more.&#39;,<br>    canonical: `${BASE_URL}/features`,<br>    robots: &#39;index, follow&#39;,<br>  },<br>  // ... more routes<br>};</pre><p>Key principle: Keep titles <strong>50–60 characters</strong>. This ensures full display in search results.</p><p><strong>Step 2: Build the injection function</strong></p><pre>function injectSeoMeta(urlPath, html) {<br>  const meta = getMetaForRoute(urlPath);<br>  if (!meta) return html;</pre><pre>  const injection = `<br>    &lt;title&gt;${escapeHtml(meta.title)}&lt;/title&gt;<br>    &lt;meta name=&quot;description&quot; content=&quot;${escapeHtml(meta.description)}&quot; /&gt;<br>    &lt;meta name=&quot;robots&quot; content=&quot;${meta.robots}&quot; /&gt;<br>    &lt;link rel=&quot;canonical&quot; href=&quot;${meta.canonical}&quot; /&gt;<br>    &lt;meta property=&quot;og:title&quot; content=&quot;${escapeHtml(meta.ogTitle)}&quot; /&gt;<br>    &lt;meta property=&quot;og:description&quot; content=&quot;${escapeHtml(meta.ogDescription)}&quot; /&gt;<br>    &lt;meta property=&quot;og:type&quot; content=&quot;${meta.ogType}&quot; /&gt;<br>    &lt;meta property=&quot;og:url&quot; content=&quot;${meta.canonical}&quot; /&gt;<br>    &lt;meta property=&quot;og:image&quot; content=&quot;${meta.image || OG_IMAGE}&quot; /&gt;<br>    &lt;meta property=&quot;og:image:width&quot; content=&quot;1200&quot; /&gt;<br>    &lt;meta property=&quot;og:image:height&quot; content=&quot;630&quot; /&gt;<br>    &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot; /&gt;<br>    &lt;meta name=&quot;twitter:title&quot; content=&quot;${escapeHtml(meta.ogTitle)}&quot; /&gt;<br>    &lt;meta name=&quot;twitter:description&quot; content=&quot;${escapeHtml(meta.ogDescription)}&quot; /&gt;<br>    &lt;meta name=&quot;twitter:image&quot; content=&quot;${meta.image || OG_IMAGE}&quot; /&gt;<br>  `;</pre><pre>  // Remove existing meta tags to avoid duplicates<br>  html = html.replace(/&lt;title&gt;.*?&lt;\/title&gt;/i, &#39;&#39;);<br>  html = html.replace(/&lt;meta name=&quot;description&quot;.*?&gt;/i, &#39;&#39;);<br>  html = html.replace(/&lt;link rel=&quot;canonical&quot;.*?&gt;/i, &#39;&#39;);</pre><pre>  // Inject new tags<br>  return html.replace(&#39;&lt;/head&gt;&#39;, `${injection}\n  &lt;/head&gt;`);<br>}</pre><p><strong>Step 3: Hook into your server</strong></p><pre>// server/server.js<br>app.get(&#39;*&#39;, (req, res) =&gt; {<br>  const indexPath = path.join(__dirname, &#39;../build/index.html&#39;);<br>  <br>  fs.readFile(indexPath, &#39;utf8&#39;, (err, html) =&gt; {<br>    if (err) {<br>      return res.status(500).send(&#39;Error loading page&#39;);<br>    }</pre><pre>    // Inject SEO meta tags<br>    const modifiedHtml = injectSeoMeta(req.path, html);<br>    <br>    res.send(modifiedHtml);<br>  });<br>});</pre><p>That’s it. No Puppeteer. No complex build pipeline.</p><h3>Critical SEO fixes we implemented</h3><p><strong>1. Canonical tag consolidation</strong></p><p>Problem: Multiple canonical tags on the same page.</p><p>We had canonicals in:</p><ul><li>index.html (base template)</li><li>Component-level React Helmet tags</li><li>Server-side injection</li></ul><p>Search engines received conflicting signals.</p><p>Solution: Remove all component-level canonicals. Let server-side injection handle everything.</p><pre>// BEFORE (in React components)<br>&lt;Helmet&gt;<br>  &lt;link rel=&quot;canonical&quot; href=&quot;https://www.someaningful.com/features&quot; /&gt;<br>&lt;/Helmet&gt;</pre><pre>// AFTER<br>&lt;Helmet&gt;<br>  {/* Server-side SEO handles all meta tags */}<br>&lt;/Helmet&gt;</pre><p>Impact: Eliminated duplicate content signals, consolidated link equity.</p><p><strong>2. Title tag optimization</strong></p><p>Problem: Titles too long, getting truncated in search results.</p><p>Before:</p><ul><li>“Meaningful | Contact Management App &amp; Personal Relationship Manager” (71 chars)</li><li>“Features | Meaningful — Contact Management App &amp; Personal Relationship Manager” (65 chars)</li></ul><p>After:</p><ul><li>“Meaningful | Personal CRM &amp; Contact Manager” (48 chars)</li><li>“Features | Meaningful Personal CRM” (36 chars)</li></ul><p>Rule: Keep titles between 50–60 characters. Every character counts in search results.</p><p><strong>3. Domain consistency</strong></p><p>Problem: Mixed usage of <a href="http://www.someaningful.com/">www.someaningful.com</a> and someaningful.com.</p><p>Solution:</p><ol><li>Choose one canonical version (we chose non-www)</li><li>Update all canonical URLs to match</li><li>Implement 301 redirects at server level</li></ol><pre>// Redirect www to non-www<br>app.use((req, res, next) =&gt; {<br>  if (req.headers.host.startsWith(&#39;www.&#39;)) {<br>    return res.redirect(301, `https://${req.headers.host.slice(4)}${req.url}`);<br>  }<br>  next();<br>});</pre><p><strong>4. Schema markup</strong></p><p>Add structured data for rich snippets:</p><pre>schema: JSON.stringify({<br>  &#39;@context&#39;: &#39;https://schema.org&#39;,<br>  &#39;@type&#39;: &#39;SoftwareApplication&#39;,<br>  name: &#39;Meaningful&#39;,<br>  applicationCategory: &#39;BusinessApplication&#39;,<br>  offers: {<br>    &#39;@type&#39;: &#39;Offer&#39;,<br>    price: &#39;0&#39;,<br>    priceCurrency: &#39;EUR&#39;,<br>  },<br>  aggregateRating: {<br>    &#39;@type&#39;: &#39;AggregateRating&#39;,<br>    ratingValue: &#39;4.8&#39;,<br>    ratingCount: &#39;127&#39;<br>  }<br>})</pre><p>This gets you rich snippets in search results — star ratings, pricing, app category.</p><h3>Dynamic routes (blog posts)</h3><p>For dynamic content like blog posts, generate meta tags on the fly:</p><pre>function getMetaForRoute(urlPath) {<br>  // Static routes<br>  if (STATIC_META[urlPath]) {<br>    return STATIC_META[urlPath];<br>  }</pre><pre>  // Dynamic blog posts<br>  const blogMatch = urlPath.match(/^\/blog\/([a-z0-9-]+)$/);<br>  if (blogMatch) {<br>    const slug = blogMatch[1];<br>    const post = BLOG_POSTS.find(p =&gt; p.slug === slug);<br>    <br>    if (post) {<br>      return {<br>        title: `${post.title} | Meaningful Blog`,<br>        description: post.excerpt,<br>        canonical: `${BASE_URL}/blog/${slug}`,<br>        image: post.image || OG_IMAGE,<br>        ogType: &#39;article&#39;,<br>        robots: &#39;index, follow&#39;,<br>        articlePublishedTime: post.date,<br>        articleAuthor: &#39;Meaningful Team&#39;,<br>        schema: JSON.stringify({<br>          &#39;@context&#39;: &#39;https://schema.org&#39;,<br>          &#39;@type&#39;: &#39;BlogPosting&#39;,<br>          headline: post.title,<br>          datePublished: post.date,<br>          author: { &#39;@type&#39;: &#39;Organization&#39;, name: &#39;Meaningful&#39; },<br>          image: post.image,<br>        })<br>      };<br>    }<br>  }</pre><pre>  return null;<br>}</pre><h3>Testing your implementation</h3><p><strong>View source test</strong></p><p>Visit your page, right-click → View Page Source. You should see:</p><pre>&lt;head&gt;<br>  &lt;title&gt;Your Optimized Title&lt;/title&gt;<br>  &lt;meta name=&quot;description&quot; content=&quot;Your description&quot; /&gt;<br>  &lt;link rel=&quot;canonical&quot; href=&quot;https://yourdomain.com/page&quot; /&gt;<br>  &lt;!-- All meta tags visible in source --&gt;<br>&lt;/head&gt;</pre><p>If you only see &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;, your injection isn&#39;t working.</p><p><strong>Google rich results test</strong></p><p>Visit: <a href="https://search.google.com/test/rich-results">https://search.google.com/test/rich-results</a></p><p>Enter your URL. You should see:</p><ul><li>Valid schema markup</li><li>All meta tags detected</li><li>Preview of how it appears in search</li></ul><p><strong>Facebook sharing debugger</strong></p><p>Visit: <a href="https://developers.facebook.com/tools/debug/">https://developers.facebook.com/tools/debug/</a></p><p>Test your Open Graph tags. You should see:</p><ul><li>Correct title</li><li>Correct description</li><li>Image preview (1200×630px)</li></ul><p><strong>LinkedIn post inspector</strong></p><p>Visit: <a href="https://www.linkedin.com/post-inspector/">https://www.linkedin.com/post-inspector/</a></p><p>Verify your content previews correctly when shared.</p><h3>Common pitfalls to avoid</h3><p><strong>Forgetting to escape HTML</strong></p><p>Always escape user-generated content in meta tags:</p><pre>function escapeHtml(text) {<br>  const map = {<br>    &#39;&amp;&#39;: &#39;&amp;amp;&#39;,<br>    &#39;&lt;&#39;: &#39;&amp;lt;&#39;,<br>    &#39;&gt;&#39;: &#39;&amp;gt;&#39;,<br>    &#39;&quot;&#39;: &#39;&amp;quot;&#39;,<br>    &quot;&#39;&quot;: &#39;&amp;#039;&#39;<br>  };<br>  return text.replace(/[&amp;&lt;&gt;&quot;&#39;]/g, m =&gt; map[m]);<br>}</pre><p><strong>Duplicate canonical tags</strong></p><p>Only one canonical per page. Remove all others:</p><pre>// Remove ALL existing canonicals before injecting<br>html = html.replace(/&lt;link rel=&quot;canonical&quot;.*?&gt;/gi, &#39;&#39;);</pre><p><strong>Wrong OG image size</strong></p><p>Social platforms require <strong>1200×630px</strong>. Not 1024×1024. Not 800×600.</p><pre># Resize with ImageMagick<br>convert logo.png -resize 1200x630 -gravity center -extent 1200x630 og-image.png</pre><p><strong>Mixing www and non-www</strong></p><p>Pick one. Stick with it. Redirect the other.</p><h3>Results we achieved</h3><p>Before:</p><ul><li>Empty pages in Google Search Console</li><li>0 impressions for most pages</li><li>No social media previews</li></ul><p>After (30 days):</p><ul><li>All pages indexed correctly</li><li>+47% organic traffic</li><li>Rich snippets appearing for blog posts</li><li>Social shares showing correct previews</li></ul><p>After (90 days):</p><ul><li>+156% organic traffic</li><li>Top 10 rankings for “personal CRM”</li><li>23 referring domains from content syndication</li></ul><h3>The backlink strategy</h3><p>SEO isn’t just technical. You need backlinks.</p><p>Here’s what worked for us:</p><p><strong>Tier 1: Quick wins (0–30 days)</strong></p><p>Submit to directories:</p><ul><li>Product Hunt</li><li>Hacker News (Show HN)</li><li>Indie Hackers</li><li>BetaList</li></ul><p>Syndicate content:</p><ul><li>Republish blog posts on Medium (with canonical back to your site)</li><li>Cross-post to Dev.to</li><li>Share on HackerNoon</li><li>LinkedIn articles</li></ul><p>Founder personal branding:</p><ul><li>LinkedIn posts (2–3x/week) linking to blog</li><li>Twitter threads with blog links</li><li>Quora answers</li></ul><p><strong>Tier 2: Content marketing (30–90 days)</strong></p><p>Comparison content:</p><ul><li>“Tool A vs Tool B” posts</li><li>Target high-intent keywords</li><li>Include your product as alternative</li></ul><p>Guest posts:</p><ul><li>Target high-DR sites in your niche</li><li>Provide genuine value</li><li>Include natural backlink</li></ul><p>Original research:</p><ul><li>Conduct industry survey</li><li>Publish findings</li><li>Earn backlinks from citations</li></ul><h3>Tools you need</h3><p>Free:</p><ul><li>Google Search Console (track rankings, impressions)</li><li>Google Rich Results Test (validate schema)</li><li>Facebook Sharing Debugger (test OG tags)</li><li>LinkedIn Post Inspector (test LinkedIn previews)</li></ul><p>Paid (optional):</p><ul><li>Ahrefs ($99/mo) — backlink monitoring, keyword research</li><li>SEMrush ($119/mo) — competitor analysis, rank tracking</li></ul><h3>Deployment checklist</h3><p>Before you deploy:</p><ul><li>All titles 50–60 characters</li><li>All meta descriptions 150–160 characters</li><li>Single canonical tag per page</li><li>OG image is 1200×630px</li><li>Schema markup validates</li><li>301 redirects configured (www → non-www)</li><li>Sitemap.xml submitted to Search Console</li><li>Robots.txt allows crawling</li></ul><p>After deployment:</p><ul><li>View source on all public pages</li><li>Test with Google Rich Results Test</li><li>Test social sharing on Facebook, LinkedIn, Twitter</li><li>Monitor Search Console for errors</li><li>Request re-indexing for modified pages</li></ul><h3>Why this matters</h3><p>SEO isn’t about gaming the system. It’s about making your content accessible.</p><p>When you fix your SEO:</p><ul><li>Users find you through search</li><li>Your content gets shared correctly on social media</li><li>Search engines understand what you offer</li><li>You build organic, sustainable traffic</li></ul><p>And you do it without rewriting your entire app or spinning up headless browsers.</p><h3>The bottom line</h3><p>Server-side meta injection is:</p><ul><li>Simple — ~500 lines of code</li><li>Reliable — No Puppeteer failures</li><li>Fast — No rendering overhead</li><li>Effective — Crawlers see everything</li></ul><p>We went from 0 organic traffic to ranking in the top 10 for our primary keywords in 90 days.</p><p>The code is straightforward. The results are real.</p><p>If you’re building a React app and struggling with SEO, this is your solution.</p><p>Try <strong>Meaningful</strong> — the personal CRM built for individuals, not sales teams. Free during <strong>Alpha</strong>. <a href="https://someaningful.com/">https://someaningful.com</a></p><p>Building in public? Follow our journey on LinkedIn: <a href="https://www.linkedin.com/company/someaningful/">https://www.linkedin.com/company/someaningful/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ba8bde1331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEO not DEAD ✅]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/seo-not-dead-a3063a15238d?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3063a15238d</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[seo-tips-and-tricks]]></category>
            <category><![CDATA[search-optimization]]></category>
            <category><![CDATA[seo-tips]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 10:06:01 GMT</pubDate>
            <atom:updated>2024-02-20T10:06:01.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Some of you might remember the article I wrote last time: <a href="https://edu.berrynews.org/seo-is-dead.html"><em>SEO is DEAD ❌</em></a><em> </em>, it was extremely productive and even though the like vs dislike proportion favors the latter many of you provided valuable insight into how to improve berrynews.org SEO ranking and Domain Authority, thank you for that.</p><p>Based on your replies I’ve compiled a list of how to optimize your SEO and although many had a valid point, a platform which aggregates news articles from various sources would be close to impossible to improve, I want to consider it as a challenge🦾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*xQ82iELYtLLwRDSn.jpg" /></figure><h3>What actions should I take?</h3><p>This brings me to the first actionable improvement point:</p><ol><li>Patience is key: Understand that SEO takes time. Two weeks is typically not long enough to see significant results, especially for keywords with high search volumes. I’ll post an update once more time has passed and I’ve had the time to develop more the SEO</li><li>Focus on relevant keywords: Target relevant search queries. Being on the first page for low-volume searches won’t drive much traffic. Aim for higher-volume, relevant keywords. Keyword optimization is an important factor and you have built-in tools in Google Search and Bing Search where you can find out what would work best for your website and update the metadata accordingly.</li><li>SEO is a comprehensive strategy: Optimize beyond just page speed. Focus on creating great content, building domain authority, acquiring quality backlinks, and setting up technical aspects like metadata and sitemaps properly. On backlinks I will explain more further down but if you’re a curious one use this #</li><li>Competitive niches require more effort: SEO in highly competitive sectors, like news, demands more work and strategic planning. Truer words have never been spoken, as I said challenge ACCEPTED🫡</li><li>Invest time in SEO: Dedicate time to understanding and implementing SEO best practices, including meta tags, content writing, and backlink strategies. Results will show over time. I’ve just finished reading “The Beginner’s Guide to SEO” by MOZ and now moved to “Search Engine Optimization (SEO) Starter Guide” from Google Search.</li><li>Set realistic expectations: Adjust your expectations for SEO outcomes. Initial traffic might be low, and growth is typically incremental. Consistent effort is required to see improvements and we shall see this in a couple of months when I post the update.</li><li>Long-term strategy: Plan for SEO as a long-term strategy, giving it a few months to start showing results. Early expectations for quick gains are often unrealistic. This was one extremely valid but hard to achieve bullet point that I am working on.</li></ol><p>tl;dr: These points emphasize the importance of patience, relevant content targeting, comprehensive SEO strategies, and setting realistic expectations in the competitive landscape of online content.</p><h3>How exactly do you improve SEO?</h3><ol><li>🧘</li><li>Keyword research: if you want the full-length version you can find it <a href="https://moz.com/beginners-guide-to-seo/keyword-research">here</a>. I will try as best as possible to answer these questions for myself, but they are a blueprint for any SEO improvements.</li><li>Ask what your users want?</li></ol><ul><li>Ad-free news</li><li>Time efficiency: A single platform to host them all</li><li>Multiple sources and languages</li><li>Unfiltered content</li></ul><ol><li>What are your users searching for?</li></ol><ul><li>TBD</li></ul><ol><li>How often are your users searching the terms?</li><li>Top 10 is unachievable but top 100 is more than better</li><li>What is your competition doing?</li></ol><ul><li>Keywords by competitor</li></ul><ol><li>Keywords by season</li></ol><ul><li>Is it Christmas already?🎅</li></ul><ol><li>Keywords by region</li><li>(Bonus) What type of search types do we have?</li></ol><ul><li>Informational queries — how fall is Brad Pitt</li><li>Navigational queries — just Google search “berry news” if you don’t know the full link</li><li>Transactional queries: buy concert ticket</li><li>Commercial research</li><li>Local queries: best oliebollen in Den Haag?</li></ul><ol><li>Tools:</li></ol><ul><li><a href="https://moz.com/explorer">Moz Keyword Explorer</a> — (PAID) The tool extracts accurate search volume data by using live clickstream data.</li><li><a href="https://ads.google.com/intl/en_us/home/tools/keyword-planner/">Google Keyword Planner</a> — (FREE) Google’s AdWords Keyword Planner has historically been the most common starting point for SEO keyword research.</li><li><a href="https://trends.google.com/trends/?geo=US">Google Trends</a> — Google’s keyword trend tool is great for finding seasonal keyword fluctuations.</li><li><a href="https://answerthepublic.com/">AnswerThePublic</a> — This free tool populates commonly searched for questions around a specific keyword.</li><li><a href="https://www.spyfu.com/">SpyFu Keyword Research Tool</a> — Provides some really neat competitive keyword data.</li></ul><ol><li>Backlink strategy is an essential component of SEO, as backlinks (links from other websites to yours) are a significant ranking factor for search engines. Developing an effective backlink strategy:</li></ol><p><strong>Understanding backlinks</strong></p><ol><li>Quality over quantity: One high-quality backlink from a reputable site is worth more than many low-quality links from dubious sources.</li><li>Relevance: Backlinks from sites within your niche or industry are more beneficial as they are seen as more relevant.</li><li>Diverse Link Profile: A natural backlink profile has links from various sources and types (e.g., blogs, news sites, educational sites).</li></ol><p><strong>Content creation</strong></p><ol><li>Valuable content: Create high-quality, informative, and engaging content that others naturally want to link to.</li><li>Shareable assets: Infographics, research studies, comprehensive guides, and thought leadership articles are examples of content that typically attract backlinks. As recently “announced” berrynews Europe and Spain “article share feature”</li></ol><p><strong>Outreach and networking</strong></p><ol><li>Blogger outreach: Reach out to bloggers or influencers in your industry for guest posting opportunities or to share your content.</li><li>Relationship building: Develop relationships with industry leaders and content creators. Networking can lead to organic backlinks.</li></ol><p><strong>Utilize social media and forums</strong></p><ol><li>Share your content on social media platforms and relevant online communities. While most social media links are nofollow, they can lead to exposure and natural backlinking.</li></ol><p><strong>Broken link building</strong></p><ol><li>Identify broken links on other websites and suggest your content as a replacement. To be honest, this one I didn’t properly understand.</li></ol><p><strong>Guest blogging</strong></p><ol><li>Write articles for other websites in your industry. Include a link back to your website within the content or in your author bio. If anyone wants to connect you can find me at @email</li></ol><p><strong>Leverage PR and publicity</strong></p><ol><li>Utilize press releases or reach out to news outlets for coverage of significant events, studies, or announcements from your company.</li></ol><p><strong>Monitor your backlink profile</strong></p><ol><li>Use tools like <a href="https://ahrefs.com/">Ahrefs</a>, <a href="https://www.semrush.com/">SEMrush</a>, or <a href="https://moz.com/">Moz</a> to monitor your backlinks. Keep an eye out for spammy links that might harm your site’s reputation.</li></ol><p><strong>Competitor analysis</strong></p><ol><li>Analyze the backlink profiles of your competitors to understand where they are getting their links from. This can provide ideas for your own strategy.</li></ol><p><strong>Be Active in industry forums and blogs</strong></p><ol><li>Participate in discussions on industry forums and comment on relevant blogs. Make sure your contributions are meaningful; this can lead to natural backlink opportunities.</li></ol><p><strong>Directories and listings</strong></p><ol><li>Get listed in reputable directories relevant to your industry. Avoid low-quality directories as they can be harmful.</li></ol><p><strong>Best practices and caution</strong></p><ol><li>Avoid black-hat techniques: Buying links, participating in link schemes, or excessive link exchanges can lead to penalties from search engines.</li><li>Natural growth: Build your backlinks gradually and naturally. A sudden spike in backlinks can appear manipulative to search engines.</li><li>Focus on value: Always focus on providing value through your content and interactions. High-quality content that serves the user’s needs is more likely to earn backlinks.</li></ol><p>Developing a strong backlink profile takes time and effort, but it’s a vital part of a comprehensive SEO strategy. Remember, the goal is to build a natural-looking backlink profile that grows organically over time.</p><p>This brings my article to an end.</p><p>If you are not familiar with some of these terms, I suggest that you check out the <a href="https://moz.com/beginners-guide-to-seo/seo-glossary">Glossary</a>. And this funny message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I8YoRWY_s5YucZJb.jpeg" /></figure><p>As always, thank you stranger for your time and if you want to “make acquaintance” you can always follow to my medium account.</p><p>Until next time much love from Den Haag 🫶</p><h3>Bogdan Tudorache | Founder of berrynews.org</h3><p>👏 Find this helpful? [clap]</p><p>🔔 Stay in touch? [follow <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache </a>]</p><p>🤝 Connect? [ <a href="https://www.linkedin.com/in/bogdan-tudorache/">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/s/s9ulhUlDza">Reddit</a> ]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3063a15238d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEO is DEAD ❌]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/seo-is-dead-393ee6b88dcc?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/393ee6b88dcc</guid>
            <category><![CDATA[seo-tips]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 19:13:59 GMT</pubDate>
            <atom:updated>2023-11-21T19:13:59.845Z</atom:updated>
            <content:encoded><![CDATA[<p>For the past 2 weeks I’ve been extremely focused on dev work for <a href="https://berrynews.org/">BerryNews.org</a>, OBSSESIVELY.</p><p>I’m going to be brutally honest and transparent in everything I’m going to share.</p><p>Generally speaking, if we do not count users that have ad blockers, threat protection or utilize browsers such as Brave, there is quite little traffic going to my website, quite unfortunate but then again this is a tech hobby and I’m not one bit upset about it.</p><p><strong>Side note: </strong>although I have tried GoogleAds, they proved unsuccessful and I had 2–3 paid visit at a massive cost of 50c/click.</p><p>My goal has been to learn, to develop myself and to challenge what you can do with a SBC – single board computer.</p><p><strong>Side note: </strong>So far, I’m genuinely impressed, a bit afraid that the SD card will get corrupted so I regularly back-up.</p><p>There is nothing better than proper planning.</p><p>Below you will see a snapshot of roughly 28 days of website visits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*Tn6_D4Jpw_es0ZBgWzWFtA@2x.jpeg" /></figure><p>At the end of October I started my intense work, and funny enough it was on SEO —Search Engine Optimization, in short for those that do not know what it means I’m making the webpages more attractive for web crawlers so that search engines will display them first.</p><p>As you can see, around 5th of November a massive spike, I was so happy, after all my hard work, I’ll be getting more traffic, more exposure and more chances for feedback, which is ultimately what would push any real growth.</p><p>The victory was short lived and I returned to the normal trends, but why?</p><p>I was furious, it does not make sense, now I score 98/100 for SEO on any auditing tool (ex. Lighthouse), then I started researching on reddit and I stumbled upon an adjacent SEO article for web3/blockchain/crypto.</p><p>“62% of Funded Blockchain and Web3 Companies Attract Fewer Than 100 Monthly Organic Visitors”</p><blockquote>So, real companies, with funding money get 100 organic visitors per month, same as me, wow.</blockquote><p>You can read the whole article on their website:</p><p>https://guerrillabuzz.com/62-of-funded-blockchain-and-web3-companies-attract-fewer-than-100-monthly-organic-visitors/#Research-Objectives</p><p>But in <strong>summary</strong>:</p><p>The analysis centers on a dataset comprising 6,734 blockchain and web3 companies, encompassing both emerging startups and well-established industry entities that have secured funding at different stages of their development. The primary emphasis is on evaluating their web traffic, particularly organic visitors, to gauge post-funding growth and consumer interest.</p><p>Although the article focuses only on niche tech, I believe the results to be universally applicable:</p><p>🔵 The market is simply oversaturated</p><p>🔵 There are so many apps which are fighting for your attention</p><p>🔵 There are so many websites to read, follow not to mention social media and their teams of behavioral psychologists</p><p>🔵 Launching a website with almost 0 skills is a days work, don’t get me stated with low-code/no-code..</p><p>🔵 Generally speaking, you need to either pay for views or have a massive following.</p><p>In the end, I think the snapshot is a testament of each and every one of you who have been following me in my journey, the 5 minutes you spared in your busy schedule, reading this post, visiting the website, to liking or commenting.</p><p>Every one of your interactions fuels my journey.</p><p>Thank you!</p><h3>Bogdan Tudorache | Founder of berrynews.org</h3><p>👏 Find this helpful? [clap]</p><p>🔔 Stay in touch? [follow <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache </a>]</p><p>🤝 Connect? [<a href="https://www.linkedin.com/in/bogdan-tudorache?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=ios_app">Linkedin</a> | <a href="https://www.reddit.com/u/bogdantudorache/s/s9ulhUlDza">Reddit</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=393ee6b88dcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 19: Kitty and a tree ]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-19-kitty-and-a-tree-34ab8f13a6ab?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ab8f13a6ab</guid>
            <category><![CDATA[coding-challenge]]></category>
            <category><![CDATA[tree-traversal]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 18:46:37 GMT</pubDate>
            <atom:updated>2023-10-22T18:46:37.911Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 19 of my 30-days of Python coding challenge, we dive into a tree traversal problem: Kitty needs to calculate a mathematical expression for each set of nodes. We will tackle this challenge from HackeRank in more ways than one and trust me when I say it will be one of the most difficult problems!</h4><p>Somehow, we always end up traversing trees. This time it’s a breadth-first traversal, also known as a level-order traversal. Note, however, that ‘bottom-up level order’ is typically a variation where the traversal starts from the bottom-most level of the tree and moves upward.</p><p>You can find more details in a previous article of mine, I do not deep dive into details but it’s a good starting point:</p><p><a href="https://medium.com/@tudorache.a.bogdan/traversing-a-tree-data-structure-4df9ab5045">Traversing a Tree (Data Structures)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RdzQZkOPiwehdfx3Wnw01w.png" /><figcaption>Kitty and a tree</figcaption></figure><p>This time there is no room for story telling so let’s jump into:</p><h4>The problem:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xKExxJxR15erDChNu-FPFA.png" /></figure><p>Please make sure to read the requirements for input and constraints, especially since both n and qcan go up to 10⁵.</p><p>What we need to do is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Xocp5IIXOf86cRuXtCBJWA.png" /></figure><p><a href="https://www.hackerrank.com/challenges/kittys-calculations-on-a-tree/problem">Kitty&#39;s Calculations on a Tree | HackerRank</a></p><h4>The 1st Solution:</h4><p>You can call it: “The Brute Force”, and no wonder it fails all but 1 test.</p><pre>import itertools<br><br>MOD = 10**9 + 7  # Constant for modulo operation to prevent overflow<br><br># TreeNode class represents a node in an undirected tree.<br>class TreeNode:<br>    def __init__(self):<br>        # List to store neighboring nodes or children.<br>        self.children = []  <br><br># Given the edges of the tree, this function constructs and returns the tree representation.<br>def build_tree(edges):<br>    # Dictionary comprehension to initialize all tree nodes.<br>    nodes = {i: TreeNode() for i in range(1, len(edges) + 2)}<br>    for u, v in edges:<br>        nodes[u].children.append(v)  # Add v as a child of u<br>        nodes[v].children.append(u)  # Add u as a child of v (because it&#39;s an undirected tree)<br>    return nodes<br><br># Recursive function to determine the distance between nodes u and v.<br>def distance(u, v, nodes, visited):<br>    if u == v:<br>        return 0  # If the nodes are the same, distance is 0<br>    visited[u] = True  # Mark the node as visited<br>    for child in nodes[u].children:<br>        if not visited[child]:  # If child node hasn&#39;t been visited yet<br>            dist = distance(child, v, nodes, visited)  # Recursive call to find distance from child to v<br>            if dist is not None:<br>                return dist + 1  # Add 1 to the distance for the current edge<br>    # Return None if v is not reachable from u<br>    return None  <br><br># Reading input<br>n, q = map(int, input().split())<br>edges = [tuple(map(int, input().split())) for _ in range(n-1)]<br>nodes = build_tree(edges)  # Construct the tree from the edges<br><br># For each query<br>for _ in range(q):<br>    k = int(input())<br>    query_nodes = list(map(int, input().split()))<br>    # Compute all possible combinations of 2 nodes<br>    combinations = list(itertools.combinations(query_nodes, 2))  <br>    <br>    # Calculate the required sum for the query using the formula<br>    result = sum([a * b * distance(a, b, nodes, {i: False for i in range(1, n+1)}) for a, b in combinations]) % MOD<br>    print(result)</pre><ol><li>Build the tree.</li><li>For each query set of nodes:</li></ol><ul><li>Generate all combinations of two nodes using itertools.combinations.</li><li>For each combination, calculate a x b x distance(a,b)and accumulate the sum.</li><li>Take the accumulated sum modulo 10⁹ +7 and output.</li></ul><h4><strong>The 2nd Solution:</strong></h4><p>We are hitting the time limits, which clearly spells out that our algorithm is not efficient enough, especially with the way distances are being calculated between nodes.</p><p>Ok, so this solution failed what should we do next: multiprocessing or a tree traversal algorithm?</p><ul><li>maybe for the IDE but not for hackerank, I don’t think it will support multiprocessing.</li></ul><p>An algorithmic optimization would be more appropiate and efficient way of tackiling this problem. Specifically, tree traversal algorithms and pre-computation of certail values can reduce overall time complexity.</p><p><strong>The approach:</strong></p><ol><li><strong>Precompute depth for each node</strong>: using <em>Depth First Search</em>(<em>DFS</em>) we precompute and store the depth of each node in the tree. This way we can determine the <em>Lowest Common Ancestor</em>(<em>LCA</em>) of 2 nodes.</li><li><strong>Precompute LCA using binary lifting</strong>: binary lifting can find the LCA of any 2 nodes in logarithmic time. The idea is to precompute the ancestor of every node to the powers of 2 : 2⁰,2¹,2².. 2^n which are less than the maximum depth of the tree.</li><li>Efficiently calculate distance: once we have the LCA of 2 nodes u and v , the distance between them can be found as: distance(u,v) = depth[u] + depth[v] - 2*depth[lca(u,v)].</li></ol><p><em>Short detour.</em></p><h4><strong>What is binary lifting?</strong></h4><p>Binary Lifting is an advanced technique used in the field of algorithms and data structures, especially for tree structures.</p><p>It is primarily employed to find the lowest common ancestor (LCA) of 2 nodes in a tree, particularly in a binary tree, in logarithmic time complexity.</p><p><strong>Basic Concept:</strong></p><ol><li>Preprocessing:</li></ol><ul><li>For each node, precompute its ancestor at all powers of two that are less than the height of the tree. For instance, for each node, we’ll compute its 1st, 2nd, 4th, 8th, … ancestor.</li><li>This is typically stored in a two-dimensional array, where dp[i][j] denotes the 2^j-th ancestor of node i.</li></ul><p>2. Querying:</p><ul><li>To find the LCA of 2 nodes, say u and v, first make sure they are at the same depth. This can be done by lifting the deeper node up until it&#39;s at the same depth as the shallower node.</li><li>Then, repeatedly lift both nodes using their highest ancestor that isn’t a common ancestor. By the end, the nodes will have been lifted directly below their LCA.</li><li>Finally, their next ancestor will be the LCA.</li></ul><blockquote>“Lifting the node” describes the process of moving upwards in the tree hierarchy from a given node to its ancestors.</blockquote><blockquote>In binary lifting, the term “lift” specifically refers to moving from a node to one of its ancestors at a predefined distance, often a power of two.</blockquote><blockquote>The “binary” in binary lifting comes from the idea of representing the distance we want to lift in binary form. Each bit in this binary representation corresponds to a potential jump or lift in the tree.</blockquote><p><strong>Steps in Binary Lifting:</strong></p><ol><li>Depth Calculation: Calculate the depth of each node using DFS.</li><li>Initialization: Set dp[i][0] as the direct parent of node i.</li><li>Pre-computation: For each power of 2, compute the ancestors for all nodes. For example, the 4th ancestor (2^2 = 4) can be found by looking at the 2nd ancestor of the 2nd ancestor.</li></ol><pre>for j in range(1, logN):<br>    for i in range(1, n+1):<br>        dp[i][j] = dp[dp[i][j-1]][j-1]</pre><p>4. Query:</p><ul><li>If u and v are at different depths, bring them to the same depth.</li><li>Then, move them upwards in the tree until they have the same parent (which will be the LCA).</li></ul><p><em>Detour ends.</em></p><pre>import sys<br>from itertools import combinations<br><br># Increase the recursion limit to handle deeper trees<br>sys.setrecursionlimit(10**6)<br><br>class Tree:<br>    def __init__(self, n):<br>        # Initialize the tree with &#39;n&#39; nodes<br>        self.n = n<br>        self.tree = {i: [] for i in range(n)}  # Adjacency list representation<br>        self.depth = [-1] * n  # Depth of each node<br>        # Ancestor table: up[x][y] means 2^y-th ancestor of node x<br>        self.up = [[-1] * 20 for _ in range(n)]<br><br>    def add_edge(self, u, v):<br>        # Connect two nodes<br>        self.tree[u].append(v)<br>        self.tree[v].append(u)<br><br>    def dfs(self, source, parent, d):<br>        # Depth-First Search to populate depth and up (ancestor) arrays<br>        self.depth[source] = d<br>        self.up[source][0] = parent<br>        for i in range(1, 20):<br>            if self.up[source][i-1] != -1:<br>                self.up[source][i] = self.up[self.up[source][i-1]][i-1]<br>        for child in self.tree[source]:<br>            if child != parent:<br>                self.dfs(child, source, d+1)<br><br>    def lca(self, u, v):<br>        # Find the Lowest Common Ancestor (LCA) of two nodes using the up table<br>        if self.depth[u] &lt; self.depth[v]:<br>            u, v = v, u<br>        diff = self.depth[u] - self.depth[v]<br>        for i in range(20):<br>            if (diff&gt;&gt;i) &amp; 1:<br>                u = self.up[u][i]<br>        if u == v:<br>            return u<br>        for i in reversed(range(20)):<br>            if self.up[u][i] != self.up[v][i]:<br>                u = self.up[u][i]<br>                v = self.up[v][i]<br>        return self.up[u][0]<br><br>    def distance(self, u, v):<br>        # Calculate distance between two nodes as the sum of their depths minus twice the depth of their LCA<br>        return self.depth[u] + self.depth[v] - 2*self.depth[self.lca(u, v)]<br><br>    def query(self, nodes):<br>        # Compute the required query value using combinations of the given nodes<br>        comb = combinations(nodes, 2)<br>        return sum([u*v*self.distance(u-1, v-1) for u, v in comb]) % (10**9 + 7)<br><br># Main part of the code<br>n, q = map(int, input().split())<br>T = Tree(n)<br>for _ in range(n-1):<br>    u, v = map(int, input().split())<br>    T.add_edge(u-1, v-1)<br><br># Initialize depth and up arrays with DFS<br>T.dfs(0, -1, 0)<br>for _ in range(q):<br>    k = int(input())<br>    nodes = list(map(int, input().split()))<br>    print(T.query(nodes))</pre><p>This code first creates the tree and precomputes necessary data like the depth of each node and the 2^i-th ancestor of each node.</p><p>When we need to compute the distance between 2 nodes, we utilize the LCA and the precomputed depths, making this process more efficient.</p><p>This code was good but it still failed about half of the tests.</p><h4>Time to bring in C++.</h4><p>This is not my code, however I managed to translate it into python, now for the most optimal solution.</p><pre>#include&lt;bits/stdc++.h&gt;<br>using namespace std;<br>#define K 1000000007ll<br>#define L 200001<br>static int parents[L];<br>static long long children[L];<br>bool  valuesSet[200000];<br>static long long valuesSum;<br><br>int main() {<br>        ifstream fin;<br>    fin.open(&quot;input.txt&quot;);<br>    int n, q, a, b, k;<br>    int i, j;<br>    long long sum;<br>    fin &gt;&gt; n &gt;&gt; q;<br><br>    for (i = 0; i &lt; n - 1; ++i) {<br>        fin &gt;&gt; a &gt;&gt; b;<br><br>        if (a &lt; b) {<br>            parents[b] = a;<br>        } else {<br>            parents[a] = b;<br>        }<br>    }<br><br>    parents[1] = 0;<br><br>    for (i = 0; i &lt; q; ++i) {<br>        fin &gt;&gt; k;<br>        for (j = 0; j &lt;=n; ++j)<br>        valuesSet[j]=false;<br>        memset(children, 0, sizeof(long long) * n);<br>        valuesSum = 0;<br><br>        for (j = 0; j &lt; k; ++j) {<br>            fin &gt;&gt; a;<br><br>            valuesSum += a;<br>            valuesSet[a] = true;<br>        }<br>        sum = 0;<br>        for (j = n; j &gt; 0; j--) {<br>            long long a = children[j];<br><br>            if (valuesSet[j]) {<br>                a += j;<br>            }<br><br>            if (a) {<br>                long long x = ((a % K) * ((valuesSum - a) % K)) % K;<br>                sum =(sum+ x)%K;<br>            }<br><br>            children[parents[j]] += a;<br>        }<br><br>        cout &lt;&lt; sum &lt;&lt; endl;<br>    }<br>    return 0;<br>}</pre><h4><strong>The 3rd Solution</strong></h4><p>Now we have the !AHA moment and the reason I mentioned the bottom-up tree traversal.</p><pre>n, q = map(int, input().split())<br><br># Setting up the parent list and initial values<br>parents = [0] * (n + 1)<br>valuesSet = [False] * (n + 1)<br>children = [0] * (n + 1)<br><br># Reading edges and setting up the parent-child relationship<br>for _ in range(n-1):<br>    a, b = map(int, input().split())<br>    if a &lt; b:<br>        parents[b] = a<br>    else:<br>        parents[a] = b<br><br>parents[1] = 0<br><br>for _ in range(q):<br>    k = int(input())<br>    values = list(map(int, input().split()))<br><br>    # Reset valuesSet and children for each query<br>    valuesSet = [False] * (n + 1)<br>    children = [0] * (n + 1)<br>    valuesSum = sum(values)<br><br>    for v in values:<br>        valuesSet[v] = True<br><br>    sum_val = 0<br>    MOD = 10**9 + 7<br><br>    # Bottom-up traversal from leaf to root<br>    for j in range(n, 0, -1):<br>        a = children[j]<br><br>        if valuesSet[j]:<br>            a += j<br><br>        if a:<br>            x = ((a % MOD) * ((valuesSum - a) % MOD)) % MOD<br>            sum_val = (sum_val + x) % MOD<br><br>        children[parents[j]] += a<br><br>    print(sum_val)</pre><p>The logic from the C++ code:</p><ol><li>The code reads in the edges and constructs a parent list, which for each node, maintains its parent. Node 1 is taken as the root.</li><li>For each query:</li></ol><ul><li>Initializes valuesSet (a boolean array indicating if a node is in the current set) and children (an array storing the sum of values of the subtree of each node).</li><li>Reads the nodes of the set and updates valuesSum (the sum of the node values in the current set) and valuesSet.</li><li>For each node from n to 1, it calculates the product of the subtree sum (a) and the sum of values of nodes outside the subtree (valuesSum - a). This product is added to the sum.</li><li>Also, updates the children array for the parent of the current node with the subtree sum of the current node.</li><li>Outputs the sum.</li></ul><p>Now, the given C++ solution takes advantage of certain aspects of the C++ language and efficient memory management that Python inherently lacks. The logic is based on bottom-up tree traversal, which means it starts from the leaf nodes and goes up to the root, adding the values of the current subtree to its parent.</p><p>It avoids recalculating values for subtrees multiple times. Instead of trying to convert this code into python, we should incorporate its principles into our existing Python solution.</p><p>Here’s the adapted approach:</p><ol><li>For each query, initialize a list valuesSet to indicate if a node is in the current set and a list children to store the sum of values of the subtree rooted at each node.</li><li>Calculate valuesSum, which is the sum of node values in the current set.</li><li>Traverse the tree from the leaf nodes to the root (using a post-order traversal). For each node, compute the subtree sum. Update the sum using the logic in the C++ code: summing the product of the subtree sum and the difference between valuesSum and the subtree sum.</li><li>Add the current subtree sum to its parent in children.</li><li>Return the calculated sum.</li></ol><p>Even with C++ into Python and an extremely efficient solution I still can’t pass all the tests.</p><p>My solution is not far from getting 100% success rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*fIVpjBL_UCg7mem1DXTefQ.png" /></figure><p>This has been by far the most challenging problem so far, I don’t think any of the others will be so difficult but unless we finish the 30 days of coding we’ll never know.</p><p>Now I’ll leave you with a <strong>simple</strong> question:</p><h4>What do you think, should I Reveal the Solutions in Hackerank?</h4><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>👏 Find this helpful? [ <strong>clap</strong> ]</p><p>🔔 Stay in touch? [ <strong>follow</strong> <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a> ]</p><p>📰 All coding challenges? [ <strong>view list</strong> <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a> ]</p><p>🔔 Connect?[ <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a> ]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ab8f13a6ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 18: N-Queens]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-18-n-queens-aa08d8d25022?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa08d8d25022</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 10:39:02 GMT</pubDate>
            <atom:updated>2023-10-21T11:34:58.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 18: N-Queens🏰👑🐍</h3><h4>Day 18 of my 30-days of Python coding challenge, we conquer the kingdom of the N-Queens problem. This LeetCode challenge is not just about placing pieces on a board; it’s a game of wits and algorithms. Get ready for a royal coding experience!</h4><h4>Short history of chess:</h4><p>I believe that before we dive into the problem we should learn a little about the fascinating <a href="https://en.wikipedia.org/wiki/History_of_chess">history of chess</a>.</p><p>Chess is believed to have originated in India, around the 6th century AD. The game was initially called “<a href="https://en.wikipedia.org/wiki/Chaturanga">chaturanga</a>,” which translates to “<strong>four</strong> <strong>divisions of the military</strong>” in <em>Sanskrit</em>. <br>These four divisions — infantry, cavalry, elephants, and chariots — were represented by the pawn, knight, bishop, and rook, respectively. <br>The game spread to Persia, where it was called “<a href="https://en.wikipedia.org/wiki/Shatranj">shatranj</a>,” and then moved on to the Islamic world and eventually Europe. By the late 15th century, the rules were modified to closely resemble the modern game we’re familiar with today.</p><h4><strong>Awesome facts about chess </strong>♟️</h4><ol><li><strong>Deep Blue and Garry Kasparov</strong>: In 1997, IBM’s <a href="https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)">Deep Blue</a> became the first computer to defeat a reigning world chess champion, Garry Kasparov, in a six-game match.</li><li><strong>Longest game ever</strong>: The longest recorded game of chess took 20 hours and 15 minutes and stretched over 269 moves.</li><li><strong>Chess in space</strong>: In 1970, chess became the 1st game to be played in space. Cosmonauts Anatoly Yeliseyev and Nikolay Sevastyanov played against ground control during their Soyuz 9 mission.</li><li><strong>En passant</strong>: The “en passant” move can only occur immediately after a pawn moves two squares forward from its starting position and lands beside an opponent’s pawn.</li><li><strong>Youngest grandmaster</strong>: Sergey Karjakin holds the record for the youngest grandmaster in history, earning the title at just 12 years and 7 months old.</li><li><strong>Number of 1st 10 moves</strong>: It’s estimated that the number of possible ways to play the first ten moves for both sides in chess is <strong>more</strong> <strong>than the number of atoms in the observable universe</strong>!</li><li><strong>Chess and memory</strong>: Studies have shown that playing chess can improve memory, problem-solving skills, and even IQ levels.</li><li><strong>Queen’s power</strong>: Originally, the queen could only move 1 square at a time, <em>diagonally</em>. It wasn’t <strong>until</strong> the Spanish made changes to the rules in the 15th century that the queen became the <strong>powerful</strong> piece we know today.</li><li><strong>Checkmate origin</strong>: The term “checkmate” comes from the Persian phrase “Shah mat,” which means “the King is helpless.” In <strong>Romanian</strong> we also say “Şah mat”.</li><li>The Queen’s Gambit: 62 million watches during it’s first 28 days. <a href="https://ceotudent.com/en/26-amazing-facts-you-will-be-surprised-to-read-about-the-queens-gambit-series">Extra fun facts</a></li></ol><p><em>Now back to programming.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Vaq_tzgZiCtpn6McLI9J3A.png" /><figcaption>Blonde woman playing chess on a hologram board, ai generated by Midjourney</figcaption></figure><h4>What is Backtracking?</h4><p><a href="https://www.simplilearn.com/tutorials/data-structure-tutorial/backtracking-algorithm">Backtracking</a> is a general algorithm for finding all (or some) solutions to computational problems. It <strong>incrementally</strong> builds candidates to the solutions and abandons each partial candidate as soon as it determines that it cannot be extended to a valid solution. The backtracking algorithm is used in various applications, including the N-queen problem, the knight tour problem, maze solving problems, and the search for all Hamilton paths in a graph.<br>For our N-queens problem, backtracking helps us place queens on the board while respecting the game’s constraints and retracting decisions that don’t lead to a solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*-_vkrZiTE17CGZZW.png" /><figcaption>Backtracking</figcaption></figure><h4>The Problem:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*FHHDjRBWm61cL34UJJw2RA.png" /></figure><h4>The Solution:</h4><p>If you’ve never played chess then we first ask ourselves: “How do queens move?”<br>But if you read the fun facts you’d have found out that the queen can move horizontally, vertically and diagonally only since the 15th century.</p><p>This greatly complicates the problem, however it’s also one of the reasons we love chess so much!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*LY5qAa1oh3Vyr0rB3nINPw.png" /><figcaption>How the queen moves in chess</figcaption></figure><p>I’ve devised a Python solution using OOP and <strong>backtracking</strong>. At first glance, the approach may seem straightforward, but don’t be fooled — the devil is in the details!</p><pre>class Solution(object):<br>    def solveNQueens(self, n):<br>        &quot;&quot;&quot;<br>        :type n: int<br>        :rtype: List[List[str]]<br>        &quot;&quot;&quot;<br>        def is_valid(board, row, col):<br>            # Check this row on the left side<br>            for i in range(col):<br>                if board[row][i] == &#39;Q&#39;:<br>                    return False<br>            <br>            # Check upper diagonal on the left side<br>            for i, j in zip(range(row, -1, -1), range(col, -1, -1)):<br>                if board[i][j] == &#39;Q&#39;:<br>                    return False<br>            <br>            # Check lower diagonal on the left side<br>            for i, j in zip(range(row, n, 1), range(col, -1, -1)):<br>                if board[i][j] == &#39;Q&#39;:<br>                    return False<br>            <br>            return True<br>        <br>        def solve(board, col, solutions):<br>            if col &gt;= n:<br>                solutions.append([&quot;&quot;.join(row) for row in board])<br>                return<br>            <br>            for i in range(n):<br>                if is_valid(board, i, col):<br>                    board[i][col] = &#39;Q&#39;<br>                    solve(board, col + 1, solutions)<br>                    board[i][col] = &#39;.&#39;<br>        <br>        board = [[&#39;.&#39; for _ in range(n)] for _ in range(n)]<br>        solutions = []<br>        <br>        solve(board, 0, solutions)<br>        return solutions</pre><h4>Explanation:</h4><p><strong>is_valid(): </strong>This function verifies if a queen can be placed at a given (row, col) without being attacked by another queen. It checks horizontally, vertically, and diagonally for existing queens.</p><p><strong>solve(): </strong>This recursive function attempts to place a queen in each row for the current column before moving on to the next column. When it gets to the last column, it saves the board configuration as a solution.</p><p><strong>Time and Space Complexity</strong></p><ul><li>Time Complexity: Approximately O(N!)</li><li>Space Complexity: O(N²) for the bord and O(N!) for solutions</li></ul><p>Explanation on complexity:</p><p>Time Complexity: O(N!)</p><ol><li>First Level of Decision Tree: You have <em>N</em> choices for where to place the first queen.</li><li>Second Level of Decision Tree: For the next queen, you have <em>N</em>−1 remaining rows.</li><li>Third Level of Decision Tree: For the third queen, you’ll have <em>N</em>−2 remaining rows.</li><li>…</li><li>Nth Level of Decision Tree: For the Nth queen, you have 1 remaining row.</li></ol><p>So, you’d think the time complexity is O(N*(N-1)*(N-2)*…1)=O(N!)</p><p>However, due to the constraint that no two queens can attack each other, many branches of the decision tree will be pruned early, making the actual number of nodes you explore less than N!Nevertheless, the upper bound remains O(N!).</p><p>Space Complexity: O(N^2) + O(N!)</p><p>Board space: You have an NxN board, making it O(N^2).</p><p>Solution storing: in the worst scenario you can have O(N!) possible solutions.</p><p>This solution combines the elegance of backtracking with the structure of OOP, making it efficient and maintainable.</p><p>So, get your crown ready because you’re about to be the queen (or king) of coding challenges! 👑</p><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>If you like the article and would like to support me, make sure to:</p><p>👏 Find this helpful? [ <strong>clap</strong> ]</p><p>🔔 Follow me <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a></p><p>📰 Read more coding content on <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a></p><p>🔔 Connect w/ me: <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa08d8d25022" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 17: Probability of two boxes having the same number of distinct balls]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-17-probability-of-two-boxes-having-the-same-number-of-distinct-balls-93f4c791f0?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/93f4c791f0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <category><![CDATA[coding-challenge]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 18:27:23 GMT</pubDate>
            <atom:updated>2023-09-27T21:19:20.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>Day 17 of my 30-days of Python coding challenge, we dive into a <strong>probability</strong> problem: calculating the chances of two boxes having the same distinct ball count. We will tackle this challenge from LeetCode and believe me the solution won’t be in just a few lines of code! 🔮🐍📊</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7GNiF6i6afyr_BVj.png" /><figcaption>Probability like from impossible(0) to certain(1)</figcaption></figure><h4>What is a probability?</h4><p>You can find more on <a href="https://curvebreakerstestprep.com/how-to-find-probability-formula/">this</a> website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*yVXjCgjpOCnj8Grg.png" /></figure><h4>What is a multinomial theorem?</h4><p>The Multinomial Theorem is a generalization of the Binomial Theorem (which you already know from the <strong>4th</strong> grade if I remember correct), provides a formula for expanding expressions of the form (a + b)^n. <br>In the Binomial Theorem, you can see how to expand binomial expressions with two terms, such as (a + b)^n. <br>The Multinomial Theorem extends this idea to expressions with more than two terms.</p><p>How to expand expressions of the form:</p><pre>(a₁ + a₂ + a₃ + ... + aₖ)^n</pre><p>Here, a₁, a₂, a₃, ..., aₖ are constants (terms), n is a positive integer (the exponent), and k is the number of terms.</p><p>The formula for the Multinomial Theorem involves calculating the coefficients of each term in the expansion. These coefficients are often called multinomial coefficients and are represented by the symbol x₁, x₂, x₃, …, xₘ , where k₁, k₂, k₃, ..., kₘ are non-negative integers that satisfy the conditions: k₁ + k₂ + k₃ + ... + kₘ = m</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50_2IYwZStnd1FO1QG1IOg.png" /><figcaption>multinomial formula</figcaption></figure><h4>The Problem:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVEYBfF7tWqufwaPbA7xfQ.png" /></figure><p><a href="https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><h4>The Solution:</h4><p>I found this simple and elegant multinomial answer and to be honest at a first glanced it seemed impressive and smart.</p><p>The idea behind it is: using multinomial coefficients to evaluate the total number of possibilities for boxes and then divide it by the total number of possibilities. (<em>see second photo</em>)</p><pre>class Solution:<br>    def multinomial(self, n):<br>        return factorial(sum(n))/prod([factorial(i) for i in n])<br>  <br>    def getProbability(self, balls):<br>        k, n, Q = len(balls), sum(balls)// 2, 0<br>        arrays = [range(0,i+1) for i in balls]<br>        t = list(product(*arrays))<br>        for i in range(len(t)):<br>            if sum(t[i]) == n and t[i].count(0) == t[-i-1].count(0):<br>                Q += self.multinomial(t[i]) * self.multinomial(t[-i-1]) <br><br>        return Q / self.multinomial(list(balls))     </pre><p>On paper everything seemed fine and dandy but I hit an error on the first run:</p><pre>NameError: global name &#39;prod&#39; is not defined<br>    return factorial(sum(n))/prod([factorial(i) for i in n])<br>Line 3 in multinomial (Solution.py)<br>    Q += self.multinomial(t[i]) * self.multinomial(t[-i-1])<br>Line 11 in getProbability (Solution.py)<br>    ret = Solution().getProbability(param_1)<br>Line 32 in _driver (Solution.py)<br>    _driver()<br>Line 42 in &lt;module&gt; (Solution.py)</pre><p>Ok, so the Leet Code compiler doesn’t know prod that’s no biggie, we can simply replace it with functools.reduce and operator :</p><pre> return factorial(sum(n)) / reduce(operator.mul, [factorial(i) for i in n], 1)</pre><p><a href="https://docs.python.org/3/library/functools.html">functools</a></p><p><a href="https://www.geeksforgeeks.org/reduce-in-python/">reduce()</a></p><pre>The reduce(fun,seq) function is used to apply a particular function<br> passed in its argument to all of the list elements mentioned in the sequence <br>passed along.This function is defined in “functools” module.<br><br>Working :  <br><br>At first step, first two elements of sequence are picked and the result <br>is obtained.<br>Next step is to apply the same function to the previously attained result <br>and the number just succeeding the second element and the result is again <br>stored.<br>This process continues till no more elements are left in the container.<br>The final returned result is returned and printed on console.</pre><p>However now when we run the new code we get an error.</p><pre>class Solution:<br>    def multinomial(self, n):<br>         return factorial(sum(n)) / \\<br>                reduce(operator.mul,[factorial(i) for i in n], 1)<br>    <br>    def getProbability(self, balls):<br>        k, n, Q = len(balls), sum(balls)// 2, 0<br>        arrays = [range(0,i+1) for i in balls]<br>        t = list(product(*arrays))<br>        for i in range(len(t)):<br>            if sum(t[i]) == n and t[i].count(0) == t[-i-1].count(0):<br>                Q += self.multinomial(t[i]) * self.multinomial(t[-i-1]) <br><br>        return Q / self.multinomial(list(balls))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*RJdfuaxz-fy2dMrsG0zrxQ.png" /></figure><h4>Why does multinomial fail?</h4><p>The error we’ve encountered is indicative of a logical flaw in the solution. The methodology provided for computing the desired probability isn’t appropriate for all cases. Let’s dissect the approach:</p><p>1. <strong>Multinomial Coefficient Computation</strong>: The function for the multinomial coefficient seems correct, as it divides the factorial of the sum of the elements by the product of the factorial of each element.</p><p>2. <strong>Generating Possible Distributions</strong>: The approach uses itertools’s `product` to generate distributions. This means it’s creating a Cartesian product, but that might not correctly model the distribution of balls into two boxes.</p><p>3. <strong>Checking Valid Distributions</strong>: The condition sum(t[i]==n and t[i].count(0)==t[-i-1].count(0)checks whether the total balls in one distribution is n <strong>and</strong> if the number of zero counts (representing colors absent in the box) is the same in both distributions. <br>While this condition is necessary, it’s not sufficient to guarantee that the distributions are valid reflections of each other.</p><p>Given these points, the overall solution is flawed in its methodology to generate valid distributions of balls into two boxes.</p><p>To solve this, a more precise approach to generating and validating the distributions is required. What I managed to find is a Java code: which recursively attempts to place balls into two boxes, that seems to be a more accurate approach to tackle this problem.</p><h3>Java Solution:</h3><pre>class Solution {<br>    // Entry point to calculate the desired probability<br>    public double getProbability(int[] balls) {<br>        int[] firstHalf = new int[balls.length]; // Represents balls in the first box for current division<br>        int[] secondHalf = new int[balls.length]; // Represents balls in the second box for current division<br>        <br>        // Good stores the number of desired cases (both boxes having the same number of distinct balls)<br>        // All stores the number of all possible valid cases<br>        double[] good = new double[]{0.0};<br>        double[] all = new double[]{0.0};<br>        <br>        // For memoization: to avoid recalculating factorial values<br>        Map&lt;Double, Double&gt; memorizedFactorial = new HashMap&lt;&gt;();<br>        <br>        // Start DFS<br>        dfs(0, firstHalf, secondHalf, balls, good, all, memorizedFactorial);<br>        <br>        // Return probability<br>        return good[0] / all[0];<br>    }<br>    <br>    // DFS function to explore every possible way to distribute the balls into two boxes<br>    private void dfs(int i, int[] firstHalf, int[] secondHalf, int[] balls, <br>                     double[] good, double[] all, Map&lt;Double, Double&gt; memorizedFactorial) {<br>        // Base case: All ball types have been considered<br>        if (i == balls.length) {<br>            // Calculate sum of balls in each box<br>            int firstHalfSum = 0;<br>            int secondHalfSum = 0;<br>            for (int value : firstHalf) {<br>                firstHalfSum += value;<br>            }<br>            for (int value : secondHalf) {<br>                secondHalfSum += value;<br>            }<br>            <br>            // If number of balls in the two boxes are not same, return<br>            if (firstHalfSum != secondHalfSum) {<br>                return;<br>            }<br>            <br>            // Calculate number of ways this distribution can occur for both boxes<br>            double p1 = permutation(firstHalf, memorizedFactorial);<br>            double p2 = permutation(secondHalf, memorizedFactorial);<br>            <br>            // Count number of distinct balls in each box<br>            int cnt1 = 0;<br>            int cnt2 = 0;<br>            for (int value : firstHalf) {<br>                if (value &gt; 0) {<br>                    cnt1++;<br>                }<br>            }<br>            for (int value : secondHalf) {<br>                if (value &gt; 0) {<br>                    cnt2++;<br>                }<br>            }<br>            <br>            // Update the count of all valid distributions and desired distributions<br>            all[0] += p1 * p2;<br>            good[0] += (cnt1 == cnt2) ? p1 * p2 : 0.0;<br>        }<br>        else {<br>            // Recursively try every possible number of balls of the i-th type in the first box<br>            for (int j = 0; j &lt;= balls[i]; j++) {<br>                firstHalf[i] = j;<br>                secondHalf[i] = balls[i] - j;<br>                dfs(i + 1, firstHalf, secondHalf, balls, good, all, memorizedFactorial);<br>                firstHalf[i] = 0;<br>                secondHalf[i] = 0;<br>            }<br>        }<br>    }<br>    <br>    // Function to calculate number of ways a given distribution can happen (permutations)<br>    private double permutation(int[] arr, Map&lt;Double, Double&gt; memorizedFactorial) {<br>        double prod = 1.0;<br>        int sum = 0;<br>        for (int value : arr) {<br>            prod *= factorial((double)value, memorizedFactorial);<br>            sum += value;<br>        }<br>        return factorial((double)sum, memorizedFactorial) / prod;<br>    }<br>    <br>    // Function to calculate factorial, using memoization<br>    private double factorial(double value, Map&lt;Double, Double&gt; memorizedFactorial) {<br>        if (memorizedFactorial.containsKey(value)) {<br>            return memorizedFactorial.get(value);<br>        }<br>        double res = (value != 0) ? value * factorial(value - 1, memorizedFactorial) : 1.0;<br>        memorizedFactorial.put(value, res);<br>        return res;<br>    }<br>}</pre><p>The approach involves:</p><ol><li>Using depth-first search (<strong>DFS</strong>) to explore every possible way to divide the balls between the two boxes.</li><li>For each division, it calculates the number of ways this specific division can happen using permutations and updates the count for total valid divisions (all) and desired divisions (good).</li><li>The result will be good / all.</li></ol><h4>What is memoization?</h4><p>Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</p><p>In essence, memoization is a way to remember previously computed results for a given set of inputs so that we don’t have to redo the potentially expensive computation if we encounter the same inputs in the future.</p><p>Here’s a simple breakdown of how memoization is typically used:</p><ol><li><strong>Check the cache</strong>: Before computing a function’s result for a given input, check if the result for that input is already stored (cached).</li><li><strong>Compute if necessary</strong>: If the result is not in the cache, compute the result.</li><li><strong>Store the result</strong>: Once the result is computed, store it in the cache (often a data structure like a dictionary or an array), so it can be quickly retrieved the next time the function is called with the same inputs.</li><li><strong>Return the result</strong>: Return the computed result or the cached result, as applicable.</li></ol><p><strong>Memoization</strong> is also available in python as functools.lru_cache</p><p>The <a href="https://www.geeksforgeeks.org/python-functools-lru_cache/">lru_cache</a> decorator caches the results of function calls in a Least Recently Used (LRU) cache with a specified maximum size. If the cache reaches its maximum size, the least recently accessed entries are discarded.</p><p>Syntax:</p><pre>from functools import lru_cache<br><br># Unlimited cache size. You can also specify a limit.<br>@lru_cache(maxsize=None)  <br>def fibonacci(n):<br>    if n &lt;= 1:<br>        return n<br>    return fibonacci(n-1) + fibonacci(n-2)</pre><h4>Python code solution:</h4><pre>class Solution:<br>    def getProbability(self, balls: list[int]) -&gt; float:<br>        # Initialize arrays to keep track of the distribution of balls in each of the two boxes<br>        firstHalf = [0] * len(balls)<br>        secondHalf = [0] * len(balls)<br>        <br>        # Counters to keep track of the favorable outcomes (good) and total possible outcomes (all)<br>        good = [0.0]<br>        all = [0.0]<br>        <br>        # Dictionary to store the factorial values for reuse (memoization)<br>        memorizedFactorial = {}<br>        <br>        # Start the depth-first search algorithm from the first ball<br>        self.dfs(0, firstHalf, secondHalf, balls, good, all, memorizedFactorial)<br>        <br>        # Return the probability of drawing a favorable outcome<br>        return good[0] / all[0]<br><br>    def dfs(self, i, firstHalf, secondHalf, balls, good, all, memorizedFactorial):<br>        # Base case: when all balls are considered<br>        if i == len(balls):<br>            # Calculate the total number of balls in each box<br>            firstHalfSum = sum(firstHalf)<br>            secondHalfSum = sum(secondHalf)<br>            <br>            # If the two boxes don&#39;t have an equal number of balls, discard this arrangement<br>            if firstHalfSum != secondHalfSum:<br>                return<br>            <br>            # Calculate the permutations for the balls in both boxes<br>            p1 = self.permutation(firstHalf, memorizedFactorial)<br>            p2 = self.permutation(secondHalf, memorizedFactorial)<br>            <br>            # Count the distinct colors in each box<br>            cnt1 = sum(1 for value in firstHalf if value &gt; 0)<br>            cnt2 = sum(1 for value in secondHalf if value &gt; 0)<br><br>            # Update the total possible outcomes<br>            all[0] += p1 * p2<br>            # Update the favorable outcomes if the number of distinct colors is the same in both boxes<br>            good[0] += p1 * p2 if cnt1 == cnt2 else 0.0<br>        <br>        # Recursive case: distribute balls among the boxes<br>        else:<br>            for j in range(balls[i] + 1):<br>                firstHalf[i] = j<br>                secondHalf[i] = balls[i] - j<br>                # Recursively call the next ball<br>                self.dfs(i + 1, firstHalf, secondHalf, balls, good, all, memorizedFactorial)<br>                # Reset the values for the next iteration<br>                firstHalf[i] = 0<br>                secondHalf[i] = 0<br><br>    def permutation(self, arr, memorizedFactorial):<br>        # Calculate the product of factorials for the balls in the box<br>        prod = 1.0<br>        total = sum(arr)<br>        for value in arr:<br>            prod *= self.factorial(value, memorizedFactorial)<br>        <br>        # Return the permutation as (total factorial) / (product of individual factorials)<br>        return self.factorial(total, memorizedFactorial) / prod<br><br>    def factorial(self, value, memorizedFactorial):<br>        # If the factorial value is already computed, return it<br>        if value in memorizedFactorial:<br>            return memorizedFactorial[value]<br>        <br>        # Otherwise, compute the factorial (using recursion)<br>        res = value * self.factorial(value - 1, memorizedFactorial) if value != 0 else 1.0<br>        # Store the computed factorial in the dictionary for later use<br>        memorizedFactorial[value] = res<br>        return res</pre><h3>The Explanation:</h3><p><strong>Initialization</strong>:</p><p>Here, firstHalf and secondHalf are initialized to keep track of how the balls are divided into the two boxes. good stores the count of valid permutations, and all stores the count of all possible permutations. A dictionary memorizedFactorial is used for memoization of factorials to speed up computations.</p><p><strong>DFS:</strong><br>The dfs() is a recursive function used to explore all possible ways of dividing balls between the two boxes.</p><ul><li><strong>Base case</strong>: <br>If i is equal to the length of balls, it means all balls have been processed. We then check if the number of balls in firstHalf is equal to the number of balls in secondHalf. <br>If not, we return without doing anything.</li><li><strong>Recursive case</strong>: <br>For each ball color i, we try all possible ways of dividing them between the two boxes. <br>We then call the dfs function recursively with the next ball color (i + 1).</li></ul><p><strong>Permutations</strong>:</p><p>permutation() computes the number of permutations for a given configuration of balls.</p><p><strong>Factorial</strong>:</p><p>factorial() function computes factorials. memoization we discussed previosuly.</p><blockquote><strong>and</strong> now you’re probably why didn’t you use lru_cache well, Iwanted to but the LeetCode compiler <strong>didn’t support it</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*gxGegabRD7CivIhN7SULkg.png" /><figcaption>unable to import lru_cache</figcaption></figure><p>However here’s the full solution with lru_cache, we simply memoize factorial and remove all other references of memorizedFactorial</p><pre>from functools import lru_cache<br><br>class Solution:<br>    def getProbability(self, balls: list[int]) -&gt; float:<br>        firstHalf = [0] * len(balls)<br>        secondHalf = [0] * len(balls)<br>        good = [0.0]<br>        all = [0.0]<br><br>        self.dfs(0, firstHalf, secondHalf, balls, good, all)<br>        return good[0] / all[0]<br><br>    def dfs(self, i, firstHalf, secondHalf, balls, good, all):<br>        if i == len(balls):<br>            firstHalfSum = sum(firstHalf)<br>            secondHalfSum = sum(secondHalf)<br>            if firstHalfSum != secondHalfSum:<br>                return<br><br>            p1 = self.permutation(firstHalf)<br>            p2 = self.permutation(secondHalf)<br>            cnt1 = sum(1 for value in firstHalf if value &gt; 0)<br>            cnt2 = sum(1 for value in secondHalf if value &gt; 0)<br><br>            all[0] += p1 * p2<br>            good[0] += p1 * p2 if cnt1 == cnt2 else 0.0<br>        else:<br>            for j in range(balls[i] + 1):<br>                firstHalf[i] = j<br>                secondHalf[i] = balls[i] - j<br>                self.dfs(i + 1, firstHalf, secondHalf, balls, good, all)<br>                firstHalf[i] = 0<br>                secondHalf[i] = 0<br><br>    def permutation(self, arr):<br>        prod = 1.0<br>        total = sum(arr)<br>        for value in arr:<br>            prod *= self.factorial(value)<br>        return self.factorial(total) / prod<br><br>    @lru_cache(maxsize=None)<br>    def factorial(self, value):<br>        if value == 0:<br>            return 1.0<br>        return value * self.factorial(value - 1)</pre><p>Now, if we would summarize everything, this is actually a <strong>DFS</strong> problem in which we’ve added a sprinkle of math.😕</p><p><strong>Depth-First Search (DFS):</strong></p><ul><li><strong>Purpose</strong>: It is primarily used for traversing or searching through graph-like structures, such as trees and graphs. It goes as deep as possible down one path before backtracking.</li><li><strong>Strategy</strong>: DFS starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.</li></ul><p><em>Example</em>: Traversing a maze, searching through state-space problems, etc.</p><p><strong>Divide-and-Conquer:</strong></p><ul><li><strong>Purpose</strong>: It’s a technique to solve a problem by breaking it down into smaller and smaller sub-problems until the sub-problems are simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.</li><li><strong>Strategy</strong>: The main problem is divided (or “split”) into smaller sub-problems. These sub-problems are solved, typically using the same divide-and-conquer approach, and then their solutions are combined to solve the original problem.</li></ul><p><em>Example</em>: Merge sort, quicksort, Strassen’s Matrix Multiplication, etc.</p><p>Even though I didn’t want to write about the common algorithms, I believe that DFS deserves it’s own article, what do you think?</p><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>If you like the article and would like to support me, make sure to:</p><p>👏 Clap for the story (50 Claps) to help this article be featured</p><p>🔔 Follow me <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a></p><p>📰 Read more coding content on <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a></p><p>🔔 Connect w/ me: <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93f4c791f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 16: Dynamic Programming | Best Time to Buy and Sell Stock (Bonus: Binance BTC trading script)]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-16-dynamic-programming-best-time-to-buy-and-sell-stock-bonus-binance-btc-trading-script-89c87d7d0bb3?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c87d7d0bb3</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-trading]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 11:13:27 GMT</pubDate>
            <atom:updated>2023-09-15T17:04:52.746Z</atom:updated>
            <content:encoded><![CDATA[<p>I am attempting the <strong>30 days of coding challenge</strong> in python and in this article I will be trying to time the stock market by <strong>buy</strong>ing <strong>low</strong> and <strong>sell</strong>ing <strong>high</strong>.</p><p>Additionally, I’ve also posted the blueprint of a Binance trading script for BTCUSDT that cashes out when profits are 10%.</p><p><em>Disclaimer: this is no where near to actual trading scripts, however it’s a simple python challenge with a pretty solution that provides the foundational methodology for trading.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PkxRqV72wtBKvRsU" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej6dMH2ruoWeyqrBvr9g1Q.png" /></figure><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/">Best Time to Buy and Sell Stock III - LeetCode</a></p><h3>The Solution:</h3><pre>class Solution(object):<br>    def maxProfit(self, prices):<br>        &quot;&quot;&quot;<br>        :type prices: List[int]<br>        :rtype: int<br>        &quot;&quot;&quot;<br>        if len(prices) &lt; 2:<br>            return 0<br><br>        # Initialize variables to store the first and second buy and sell prices<br>        first_buy, first_sell, second_buy, second_sell = float(&#39;inf&#39;), 0, float(&#39;inf&#39;), 0<br><br>        for price in prices:<br>            # Update the first buy price to the minimum between the current first buy price and the current stock price<br>            first_buy = min(first_buy, price)<br><br>            # Update the first sell profit to the maximum between the current first sell profit and the difference between the current stock price and the first buy price<br>            first_sell = max(first_sell, price - first_buy)<br><br>            # Update the second buy price to the minimum between the current second buy price and the difference between the current stock price and the first sell profit<br>            second_buy = min(second_buy, price - first_sell)<br><br>            # Update the second sell profit to the maximum between the current second sell profit and the difference between the current stock price and the second buy price<br>            second_sell = max(second_sell, price - second_buy)<br><br>        return second_sell</pre><h3>The Explanation:</h3><ol><li>If the length of the prices array is less than 2, return 0 as no transaction can be made.</li><li>Initialize variables first_buy, first_sell, second_buy, and second_sell to track the minimum first buy price, maximum first sell profit, minimum second buy price, and maximum second sell profit, respectively. Set first_buy and second_buy to positive infinity as initial values.</li><li>Iterate through the prices array. a. Update first_buy to the minimum between the current first_buy and the current stock price. This ensures that we find the lowest possible buying price for the first transaction. b. Update first_sell to the maximum between the current first_sell and the difference between the current stock price and the first_buy price. This allows us to find the maximum profit for the first transaction. c. Update second_buy to the minimum between the current second_buy and the difference between the current stock price and the first_sell profit. This step finds the minimum cost of the second transaction after accounting for the profit from the first transaction. d. Update second_sell to the maximum between the current second_sell and the difference between the current stock price and the second_buy price. This step calculates the maximum profit for both transactions combined.</li><li>Return the second_sell variable, which represents the maximum profit after completing at most two transactions.</li></ol><h3>Conclusion:</h3><p>This solution is optimal because it has a <strong>time complexity </strong>of O(n), where n is the length of the prices array. The algorithm iterates through the prices array only <strong>once</strong>, making it<strong> highly efficient</strong>.</p><p>Additionally, the <strong>space complexity </strong>is O(1) as we only use a constant amount of additional space to store the buy and sell variables.</p><h3>BONUS:</h3><p>Python script for trading BTC on Binance and cashing out when the profit is 10%.</p><pre>pip install python-binance</pre><pre>import time<br>from binance.client import Client<br>from binance.exceptions import BinanceAPIException<br><br># Replace with your Binance API key and secret key<br>api_key = &quot;YOUR_API_KEY&quot;<br>api_secret = &quot;YOUR_API_SECRET&quot;<br><br># Initialize the Binance API client<br>client = Client(api_key, api_secret)<br><br># Set the symbol and profit target<br>symbol = &quot;BTCUSDT&quot;<br>profit_target = 1.10<br><br>def get_balance(asset):<br>    balance = client.get_asset_balance(asset=asset)<br>    return float(balance[&#39;free&#39;])<br><br>def buy_low_sell_high():<br>    # Get the available balance of USDT<br>    usdt_balance = get_balance(&quot;USDT&quot;)<br><br>    # Get the current BTC price<br>    btc_price = float(client.get_symbol_ticker_price(symbol=symbol)[&#39;price&#39;])<br><br>    # Calculate the amount of BTC to buy using the entire USDT balance<br>    btc_amount = usdt_balance / btc_price<br><br>    try:<br>        # Buy BTC<br>        buy_order = client.order_market_buy(symbol=symbol, quantity=btc_amount)<br>        print(&quot;BTC bought at&quot;, btc_price)<br><br>        # Wait for the BTC price to reach the profit target<br>        while True:<br>            current_price = float(client.get_symbol_ticker_price(symbol=symbol)[&#39;price&#39;])<br>            if current_price &gt;= btc_price * profit_target:<br>                break<br>            time.sleep(5)<br><br>        # Sell BTC<br>        sell_order = client.order_market_sell(symbol=symbol, quantity=btc_amount)<br>        print(&quot;BTC sold at&quot;, current_price)<br><br>    except BinanceAPIException as e:<br>        print(&quot;Error:&quot;, e)<br><br>if __name__ == &quot;__main__&quot;:<br>    buy_low_sell_high()</pre><p><a href="https://www.binance.com/en/activity/referral-entry/CPA?fromActivityPage=true&amp;ref=CPA_00Q10LFODW">Crypto Exchange Referral Program | Binance Official</a></p><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>If you like the article and would like to support me, make sure to:</p><p>👏 Clap for the story (50 Claps) to help this article be featured</p><p>🔔 Follow me <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a></p><p>📰 Read more coding content on <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a></p><p>🔔 Connect w/ me: <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c87d7d0bb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 15: Lists | Game of Life]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-15-lists-game-of-life-4bec22791d21?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bec22791d21</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 07:25:51 GMT</pubDate>
            <atom:updated>2023-09-15T17:04:58.611Z</atom:updated>
            <content:encoded><![CDATA[<p>I am attempting the <strong>30 days of coding challenge</strong> in python and in this article I will be playing the game of life.</p><h3>The rules:</h3><ol><li><em>Any live cell with fewer than two live neighbors dies as if caused by under-population.</em></li><li><em>Any live cell with two or three live neighbors lives on to the next generation.</em></li><li><em>Any live cell with more than three live neighbors dies, as if by over-population.</em></li><li><em>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</em></li></ol><p>An <strong>implementation</strong> of the Game of Life, you can find in a previous article:</p><p><a href="https://medium.com/@tudorache.a.bogdan/conways-game-of-life-df654d173be5">Conway’s game of life</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*SyRZeX2cexYE6ffE" /></figure><h3>The Problem:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EbZbHvhqYvdyfMJK1LlFg.png" /></figure><p><a href="https://leetcode.com/problems/game-of-life/description/">Game of Life - LeetCode</a></p><h3>The Solution(suboptimal):</h3><pre>def game_of_life(board):<br>    def count_neighbors(x, y):<br>        count = 0<br>        for i in range(-1, 2):<br>            for j in range(-1, 2):<br>                if i == 0 and j == 0:<br>                    continue<br>                nx, ny = x + i, y + j<br>                if 0 &lt;= nx &lt; len(board) and 0 &lt;= ny &lt; len(board[0]) and board[nx][ny] in (1, -1):<br>                    count += 1<br>        return count<br><br>    for i in range(len(board)):<br>        for j in range(len(board[0])):<br>            neighbors = count_neighbors(i, j)<br>            if board[i][j] == 1 and (neighbors &lt; 2 or neighbors &gt; 3):<br>                board[i][j] = -1<br>            elif board[i][j] == 0 and neighbors == 3:<br>                board[i][j] = 2<br><br>    for i in range(len(board)):<br>        for j in range(len(board[0])):<br>            if board[i][j] == -1:<br>                board[i][j] = 0<br>            elif board[i][j] == 2:<br>                board[i][j] = 1<br><br><br>############################# OOP as well: #################################<br><br>class Solution(object):<br>    def __init__(self):<br>        self.board = []<br><br>    def count_neighbors(self, x, y):<br>        count = 0<br>        for i in range(-1, 2):<br>            for j in range(-1, 2):<br>                if i == 0 and j == 0:<br>                    continue<br>                nx, ny = x + i, y + j<br>                if 0 &lt;= nx &lt; len(self.board) and 0 &lt;= ny &lt; len(self.board[0]) and self.board[nx][ny] in (1, -1):<br>                    count += 1<br>        return count<br><br>    def gameOfLife(self, board):<br>        self.board = board<br>        for i in range(len(self.board)):<br>            for j in range(len(self.board[0])):<br>                neighbors = self.count_neighbors(i, j)<br>                if self.board[i][j] == 1 and (neighbors &lt; 2 or neighbors &gt; 3):<br>                    self.board[i][j] = -1<br>                elif self.board[i][j] == 0 and neighbors == 3:<br>                    self.board[i][j] = 2<br><br>        for i in range(len(self.board)):<br>            for j in range(len(self.board[0])):<br>                if self.board[i][j] == -1:<br>                    self.board[i][j] = 0<br>                elif self.board[i][j] == 2:<br>                    self.board[i][j] = 1</pre><h3>The Explanation:</h3><ol><li>We define a helper function count_neighbors(x, y) that takes the row and column indices of a cell and returns the number of live neighbors.</li><li>We iterate through the rows and columns of the board.</li><li>For each cell, we count the live neighbors using the count_neighbors() function.</li><li>We apply the Game of Life rules using the if and elif statements. To avoid modifying the original board in place, we mark cells that should become dead with -1 and cells that should become alive with 2.</li><li>We iterate through the board again to update the cells with their new state.</li></ol><h3>The conclusion:</h3><p>This approach is efficient because it only needs to iterate through the board twice: once to calculate the new state based on the neighbors and then again to update the cells.</p><p>By marking cells with -1 and 2 instead of directly changing their state, we avoid altering the state of the board in the middle of applying the rules. This helps ensure that the rules are applied correctly and simultaneously to every cell.</p><h3>The Solution (optimal):</h3><pre>class Solution(object):<br>    def __init__(self):<br>        self.board = []<br><br>    def count_neighbors(self, x, y):<br>        directions = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i != 0 or j != 0]<br>        count = 0<br>        for dx, dy in directions:<br>            nx, ny = x + dx, y + dy<br>            if 0 &lt;= nx &lt; len(self.board) and 0 &lt;= ny &lt; len(self.board[0]) and self.board[nx][ny] in (1, -1):<br>                count += 1<br>        return count<br><br>    def gameOfLife(self, board):<br>        self.board = board<br>        next_board = [[0] * len(self.board[0]) for _ in range(len(self.board))]<br><br>        for i in range(len(self.board)):<br>            for j in range(len(self.board[0])):<br>                neighbors = self.count_neighbors(i, j)<br>                if self.board[i][j] == 1 and (neighbors == 2 or neighbors == 3):<br>                    next_board[i][j] = 1<br>                elif self.board[i][j] == 0 and neighbors == 3:<br>                    next_board[i][j] = 1<br><br>        self.board[:] = next_board</pre><h3>The Explanation:</h3><ol><li>We updated the count_neighbors method by using a list comprehension to generate the directions variable. This simplifies the code and makes it more readable.</li><li>Instead of iterating twice over the board, we create a new next_board with the same dimensions as the original board. We then fill in the new state directly in this new board based on the original board. This eliminates the need for marking cells with -1 and 2 and iterating twice.</li><li>After calculating the next state, we update the original board in-place using the slice assignment self.board[:] = next_board.</li></ol><h3>Conclusion:</h3><p>The optimized code is more concise, and the single loop reduces the number of iterations. However, it comes at the cost of increased memory usage due to the creation of the next_board. This is a trade-off between time complexity and space complexity.</p><h3>Best Solution:</h3><pre>class Solution(object):<br>    def __init__(self):<br>        self.board = []<br><br>    def gameOfLifeInfinite(self, live):<br>        ctr = collections.Counter((I, J)<br>                              for i, j in live<br>                              for I in range(i-1, i+2)<br>                              for J in range(j-1, j+2)<br>                              if I != i or J != j)<br>        return {ij<br>            for ij in ctr<br>            if ctr[ij] == 3 or ctr[ij] == 2 and ij in live}<br>    <br>    def gameOfLife(self, board):<br>        live = {(i, j) for i, row in enumerate(board) for j, live in enumerate(row) if live}<br>        live = self.gameOfLifeInfinite(live)<br>        for i, row in enumerate(board):<br>            for j in range(len(row)):<br>                row[j] = int((i, j) in live)</pre><p><a href="https://leetcode.com/problems/game-of-life/solutions/73217/infinite-board-solution/?orderBy=most_votes&amp;languageTags=python">Infinite board solution - Game of Life - LeetCode</a></p><h3><strong>Additional resources:</strong></h3><p>How the game of life was used to create art, quite interesting!</p><p><a href="https://sweetpeagallery.ca/blogs/editorial/the-game-of-life-early-generative-art">The &quot;Game of Life&quot; &amp; Early Generative Art</a></p><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>If you like the article and would like to support me, make sure to:</p><p>👏 Clap for the story (50 Claps) to help this article be featured</p><p>🔔 Follow me <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a></p><p>📰 Read more coding content on <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a></p><p>🔔 Connect w/ me: <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bec22791d21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 14: Linked lists | Remove duplicates]]></title>
            <link>https://medium.com/@tudorache.a.bogdan/day-14-linked-lists-remove-duplicates-4effad028b6f?source=rss-d32fc2c46868------2</link>
            <guid isPermaLink="false">https://medium.com/p/4effad028b6f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bogdan Tudorache]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 12:21:06 GMT</pubDate>
            <atom:updated>2023-09-15T17:04:51.410Z</atom:updated>
            <content:encoded><![CDATA[<p>I am attempting the <strong>30 days of coding challenge</strong> in python and in this article I will be attempting to delete all nodes that have duplicate numbers, leaving only the original list.</p><p>As you probably remember, I already had a challenge on Linked Lists, the first one, however at that time I didn’t think it would get this complex and I was not doing a walk on memory lane for specific data structures.</p><p>Nevertheless, I’m making it up over here. And if you feel like you know it, skip to the next section.</p><h4>Walk on memory lane: Linked Lists</h4><p>A linked list is a data structure that consists of a sequence of nodes, where each node contains some data and a reference (or pointer) to the next node in the sequence.</p><p>Unlike an array or list, the nodes in a linked list don’t have to be stored contiguously in memory. Instead, each node can be located at any arbitrary location in memory, and its reference to the next node provides a way to traverse the list.</p><p>Linked lists can be either <strong>singly linked</strong>, where each node contains a reference to only the next node, or <strong>doubly linked</strong>, where each node contains references to both the next and previous nodes.</p><p>Singly linked lists are simpler and more commonly used, while doubly linked lists offer some advantages in certain situations, such as allowing for efficient traversal in both directions.</p><p>Linked lists are often used to implement other data structures, such as stacks, queues, and hash tables; sparsely for matrices, graphs, and other complex data structures.</p><p><strong>Pseudocode:</strong></p><pre># Node class to represent each node in the linked list<br>class Node:<br>    def __init__(self, data):<br>        self.data = data<br>        self.next = None<br><br># Linked list class to manage the nodes<br>class LinkedList:<br>    def __init__(self):<br>        self.head = None<br><br>    # Insert a new node at the beginning of the list<br>    def insert_at_beginning(self, data):<br>        new_node = Node(data)<br>        new_node.next = self.head<br>        self.head = new_node<br><br>    # Insert a new node at the end of the list<br>    def insert_at_end(self, data):<br>        new_node = Node(data)<br>        if self.head is None:<br>            self.head = new_node<br>        else:<br>            current_node = self.head<br>            while current_node.next is not None:<br>                current_node = current_node.next<br>            current_node.next = new_node<br><br>    # Delete the first occurrence of a node with the given data<br>    def delete(self, data):<br>        if self.head is None:<br>            return<br>        if self.head.data == data:<br>            self.head = self.head.next<br>        else:<br>            current_node = self.head<br>            while current_node.next is not None:<br>                if current_node.next.data == data:<br>                    current_node.next = current_node.next.next<br>                    return<br>                current_node = current_node.next<br><br>    # Search for a node with the given data and return it<br>    def search(self, data):<br>        current_node = self.head<br>        while current_node is not None:<br>            if current_node.data == data:<br>                return current_node<br>            current_node = current_node.next<br>        return None</pre><h3>The Problem:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0JW9VrB6FizQc5C2hKc-A.png" /></figure><p><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/">Remove Duplicates from Sorted List II - LeetCode</a></p><h3>The Solution:</h3><pre>class Solution(object):<br>    def deleteDuplicates(self, head):<br>        &quot;&quot;&quot;<br>        :type head: ListNode<br>        :rtype: ListNode<br>        &quot;&quot;&quot;<br>        # Edge case where list is empty or has only one node<br>        if head is None or head.next is None:<br>            return head<br>        <br>        # Creating a dummy node to make deletion of first node easier<br>        dummy = ListNode(-1)<br>        dummy.next = head<br>        prev = dummy<br>        curr = head<br>        <br>        while curr:<br>            # Check if the current node is a duplicate<br>            if curr.next and curr.val == curr.next.val:<br>                # Loop until curr is pointing to the last duplicate node<br>                while curr.next and curr.val == curr.next.val:<br>                    curr = curr.next<br>                # Skip all the duplicate nodes<br>                prev.next = curr.next<br>            else:<br>                # Move prev to curr<br>                prev = curr<br>            # Move curr to the next node<br>            curr = curr.next<br>            <br>        return dummy.next</pre><h3>The Explanation:</h3><h4>How do we make sure we remove all the duplicate items?</h4><p>In the solution provided, we remove the duplicates by traversing the linked list one node at a time and checking if the current node has a duplicate value with the next node. If it does, we skip over all the duplicate nodes until we reach the last one, and then we update the prev node&#39;s next pointer to point to the node after the last duplicate node.</p><pre>while curr:<br>    if curr.next and curr.val == curr.next.val:<br>        while curr.next and curr.val == curr.next.val:<br>            curr = curr.next<br>        prev.next = curr.next<br>    else:<br>        prev = curr<br>    curr = curr.next</pre><p>The curr variable points to the current node we&#39;re examining, while the prev variable points to the node immediately preceding curr. We check if curr has a duplicate value with the next node (curr.next) using the condition if curr.next and curr.val == curr.next.val:.</p><p>If it does, we use another loop to skip over all the duplicate nodes until curr points to the last duplicate node. Then we update prev.next to point to the node after the last duplicate node using prev.next = curr.next. This effectively removes all the duplicate nodes from the linked list.</p><h3>Conclusion:</h3><p>The time complexity of this algorithm is O(n) because it traverses the list only once. The space complexity is O(1) because it only uses a constant amount of extra space regardless of the size of the list.</p><h3>Bogdan Tudorache | Founder @ berrynews.org</h3><p>If you like the article and would like to support me, make sure to:</p><p>👏 Clap for the story (50 Claps) to help this article be featured</p><p>🔔 Follow me <a href="https://medium.com/u/d32fc2c46868">Bogdan Tudorache</a></p><p>📰 Read more coding content on <a href="https://medium.com/@tudorache.a.bogdan/list/coding-challenge-8b957de3e773">Coding Challenge</a></p><p>🔔 Connect w/ me: <a href="https://www.linkedin.com/in/bogdan-tudorache">LinkedIn</a> | <a href="https://www.reddit.com/u/bogdantudorache/?utm_source=share&amp;utm_medium=ios_app&amp;utm_name=ioscss&amp;utm_content=1&amp;utm_term=1">Reddit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4effad028b6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>