LeetCode Çözümleri – 91. Decode Ways

LeetCode içerisinde bulunan “Decode Ways” sorusunun açıklaması ve çözümü. Size verilen string’in, her bir sayı alfabedeki harflerin sıralarına gelmesi ile, kaç farklı şekilde decode edilebileceği soruluyor.

► LeetCode 91. Decode Ways: https://leetcode.com/problems/decode-ways/

► Problem açıklaması:

A message containing letters from A-Z can be encoded into numbers using the following mapping:

‘A’ — “1”

‘B’ — “2”

‘Z’ — “26”

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, “11106” can be mapped into:

“AAJF” with the grouping (1 1 10 6)

“KJF” with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because “06” cannot be mapped into ‘F’ since “6” is different from “06”.

Given a string s containing only digits, return the number of ways to decode it.

The answer is guaranteed to fit in a 32-bit integer.

Example 1:

Input: s = “12”

Output: 2

Explanation: “12” could be decoded as “AB” (1 2) or “L” (12).

Example 2:

Input: s = “226”

Output: 3

Explanation: “226” could be decoded as “BZ” (2 26), “VF” (22 6), or “BBF” (2 2 6).

Example 3:

Input: s = “0”

Output: 0

Explanation: There is no character that is mapped to a number starting with 0. The only valid mappings with 0 are ‘J’ — “10” and ‘T’ — “20”, neither of which start with 0. Hence, there are no valid ways to decode this since all digits need to be mapped.

Example 4:

Input: s = “06”

Output: 0

Explanation: “06” cannot be mapped to “F” because of the leading zero (“6” is different from “06”).

Constraints:

1 <= s.length <= 100

s contains only digits and may contain leading zero(s).

HackerRank Çözümleri – Alternating Characters

HackerRank içerisinde bulunan “Alternating Characters” sorusunun açıklaması ve çözümü. Soruda size verilen string içerisinde, yan yana hiçbir karakterin aynı olmaması için kaç defa karakter silme işlemi yapmanız gerektiği soruluyor.

► HackerRank – Alternating Characters: https://www.hackerrank.com/challenges/alternating-characters/problem

► Problem açıklaması:

You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.

Your task is to find the minimum number of required deletions.

Example

s = AABAAB

Remove an A at positions 0 and 3 to make s = ABAB in 2 deletions.

Function Description

Complete the alternatingCharacters function in the editor below.

alternatingCharacters has the following parameter(s):

string s: a string

Returns

int: the minimum number of deletions required

Sample Input

5

AAAA

BBBBB

ABABABAB

BABABA

AAABBB

Sample Output

3

4

0

0

4

Sıfırdan C# Programlama Eğitim Seti – 3. Ders

Bu yayınla C# programlama dilini temelinden anlatacağım eğitim setinin üçüncü dersini tamamlamış olduk. Bu video serisi, genellikle hafta sonları Youtube üzerinde yapacağımız canlı yayınlar ile devam edecek.

3. Ders İçeriği;

Nümerik tiplerde type inference

Nümerik suffix kavramı

Tam sayı çevrimler

Noktalı sayı çevrimleri

Decimal çevrimleri

Aritmetik operatörler

Tam sayılarda Overflow mantığı

checked – unchecked kavramları

8 bit ve 16 bit tam sayılar

NaN, pozitif ve negatif sonsuz ve -0

double ve decimal karşılaştırması

Ayrıca videonun sonunda karıştırdığım 0.1f + 0.2f == 0.3f kısmının neden true olduğunu anladım. Durum şuymuş; “bunun her zaman true olacağına dair bir kesinlik yok”. Bu durumda CPU (veya sistemin tamamı) bunun nasıl hesaplanacağına kendisi karar veriyor anladığım kadarıyla. (Şu Stack Overflow sorusuna göz atabilirsiniz: https://stackoverflow.com/q/15117037/447156) Eric Lippert’in cevabını birkaç defa okumanızı tavsiye ederim, muazzam yazılmış. Ayrıca bu soruya ben de 8 sene önce cevap vermişim ama tamamen aklımdan çıkmış 🙂

Şöyle diyor üstad;

“The compiler and the runtime are permitted to do so however they feel like it at the time. They need not be consistent from machine to machine, from run to run, and so on. Since this can only make calculations more accurate this is not considered a bug. It’s a feature. A feature that makes it incredibly difficult to write programs that behave predictably, but a feature nevertheless.”

Örneğin; Rextester içerisinde (https://rextester.com/FPD61501) true döndürürken, aynı kod DotNetFiddle içerisinde (https://dotnetfiddle.net/BkaDOo) false döndürüyor. Buradan da bu durumu anlamış oluyoruz.

LeetCode Çözümleri – 977. Squares of a Sorted Array

LeetCode içerisinde bulunan “Squares of a Sorted Array” sorusunun açıklaması ve çözümü. Bu soruda size verilen sıralı bir dizide, her elemanın yine dizi içerisinde sıralı olarak “in-place” şeklinde karelerinin atanması isteniyor.

► LeetCode 977. Squares of a Sorted Array: https://leetcode.com/problems/squares-of-a-sorted-array/

► Problem açıklaması:

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]

Output: [0,1,9,16,100]

Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]

Output: [4,9,9,49,121]

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

Programlamada Fibonacci Serisi Ve Sayılarını Bulma

Programlamada fibonacci serisi ve belirli sıradaki fibonacci sayısı nasıl hesaplanır? Binet formülü kullanılarak belirli fibonacci sayısı nasıl hesaplanır?

► Fibonacci dizisi nedir? https://tr.wikipedia.org/wiki/Fibonacci_dizisi

Fibonacci dizisi, her sayının kendinden önceki ile toplanması sonucu oluşan bir sayı dizisidir. Bu şekilde devam eden bu dizide sayılar birbirleriyle oranlandığında altın oran ortaya çıkar, yani bir sayı kendisinden önceki sayıya bölündüğünde altın orana gittikçe yaklaşan bir dizi elde edilir.

        /// <summary>
        /// N adet fibonacci sayısını bir dizi olarak döner.
        /// </summary>
        static int[] Fibonacci(int n)
        {
            var fibSequence = new int[n];
            var prev = 0;
            var curr = 1;

            for(var i = 1; i < n; i++)
            {
                fibSequence[i] = curr;
                curr = curr + prev;
                prev = curr - prev;  
            }

            return fibSequence;
        }

        /// <summary>
        /// N index'li fibonacci sayısını dinamik programlama kullanarak döner.
        /// </summary>
        static int FibonacciNth(int n)
        {
            if (n == 0) return 0;
            if (n == 1) return 1;

            var curr = 1;
            var prev = 0;

            var counter = n - 1;

            while(counter > 0)
            {
                curr = curr + prev;
                prev = curr - prev;
                counter--;
            }

            return curr;
        }

        /// <summary>
        /// N index'li fibonacci sayısını Binet formülünü kullanarak döner.
        /// https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
        /// 1 ile 75 arasındaki n sayıları için geçerlidir.
        /// </summary>
        static int FibonacciNthClosedForm(int n)
        {
            var rootOfFive = Math.Sqrt(5);
            var phi = (1 + rootOfFive) / 2; // (≈ 1.61803)

            return (int)Math.Floor(Math.Pow(phi, n) / rootOfFive + 0.5);
        }

HackerRank Çözümleri – Caesar Cipher

HackerRank içerisinde bulunan “Caesar Cipher” sorusunun açıklaması ve çözümü. Soruda size verilen string’i sezar şifrelemesi ile, harflerini alfabedeki sıralarını verilen sayı kadar ötelemeniz isteniyor.

► HackerRank – Caesar Cipher: https://www.hackerrank.com/challenges/caesar-cipher-1/problem

► Problem açıklaması:

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar’s cipher (https://en.wikipedia.org/wiki/Caesar_cipher) shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Original alphabet: abcdefghijklmnopqrstuvwxyz

Alphabet rotated +3: defghijklmnopqrstuvwxyzabc

Sample Input

11

middle-Outz

2

Sample Output

okffng-Qwvb

Explanation

Original alphabet: abcdefghijklmnopqrstuvwxyz

Alphabet rotated +2: cdefghijklmnopqrstuvwxyzab

m — o

i — k

d — f

d — f

l — n

e — g

– –

O — Q

u — w

t — v

z — b

Sıfırdan C# Programlama Eğitim Seti – 2. Ders

Bu yayınla C# programlama dilini temelinden anlatacağım eğitim setinin ikinci dersini tamamlamış olduk. Bu video serisi, genellikle hafta sonları Youtube üzerinde yapacağımız canlı yayınlar ile devam edecek.

Eğitim sırasında interaktif olarak soru-cevap kısımlarımız olmakta. Bu nedenle benimle birlikte siz de kodlama yapabilirsiniz.

► Eğitim kimler için? C# dilini öğrenmek isteyen herkes için. Olabildiğince en basit seviyede anlatmaya çalışıyorum. Fakat her seviyedeki arkadaş için ideal bir eğitim seti olacağından eminim.

► Ücretsiz mi? Tamamen ücretsiz. Derslerin tamamı önce Youtube üzerinde canlı yayınla olacak, yayın bittikten sonra da düzenleme yapılıp videolar kısmından ulaşabilirsiniz.

► Canlı yayınlar ne zaman oluyor? Henüz belli değil, fakat kaçırmamak için kanala abone olmayı ve notification kısmını aktif etmenizi tavsiye ederim. Şu andaki düşüncem haftada bir canlı yayın. Eğer yoğun talep olursa haftada iki defa yapabiliriz.

► Eğitim kaç hafta sürecek? C# programlama dilinin geniş bir dil. Konu çok. Bende anlatma hevesi de öyle. Siz istedikçe, sizler talep ettikçe eğitimler devam edecek.

► Eğitimde hangi araçlar kullanıyorsun? Microsoft Visual Studio 2019 (https://visualstudio.microsoft.com/tr/), Linqpad (https://www.linqpad.net/) ve Microsoft Whiteboard (https://www.microsoft.com/tr-tr/p/microsoft-whiteboard/9mspc6mp8fm4?activetab=pivot:overviewtab) kullanıyorum.

► Eğitimde biz hangi araçları kullanabiliriz? Benim kullandığım araçları bilgisayarınıza kurmanızı tavsiye ederim, fakat bilgisayarınızda kurulu değilse online olan C# editörlerinden birini de kullanabilirsiniz. Tavsiye olarak DotNetFiddle https://dotnetfiddle.net/, Ideone https://ideone.com/, Csharppad https://csharppad.com/, Repl.it https://repl.it/languages/csharp ve Rextester https://rextester.com/ verebilirim. Hangisini seçeceğiniz tamamen size kalmış.

2. Ders İçeriği;

Anahtar sözcükler ve kullanımları

C#’ta yorumlar

Temel veri tipleri

const kullanımı

Custom tip oluşturmak

Conversation (implicit ve explicit)

Değer tipleri ve referans tipleri

Tam sayılar, noktalı sayılar

alias kullanımı

Nümerik ve binary literaller (c# 7.0)

Faydalı linkler:

► C# Keywords: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/

► Document your code with XML comments: https://docs.microsoft.com/en-us/dotnet/csharp/codedoc

► Types (C# Programming Guide): https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/

► const (C# Reference): https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const

► Casting and type conversions (C# Programming Guide): https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions

► Value types (C# reference): https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types

► Reference types (C# Reference): https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

► Integer literals: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types#integer-literals

Bit Manipülasyonları – 3. Kısım

Bit manipülasyonlarını, bilgisayar aritmetiğinde elde ettiğiniz verinin bitleri üzerinde değişiklikler/kontroller yaparak, elde etmek istediğiniz sonuca genellikle daha hızlı bir şekilde erişmenizi sağlayacak işlemler bütünü olarak adlandırabiliriz.

► Bit manipulation: https://en.wikipedia.org/wiki/Bit_manipulation

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions. Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and possibly other operations analogous to the boolean operators; there are also bit shifts and operations to count ones and zeros, find high and low one or zero, set, reset and test bits, extract and insert fields, mask and zero fields, gather and scatter bits to and from specified bit positions or fields. Integer arithmetic operators can also effect bit-operations in conjunction with the other operators.

► Bir manipülasyonları nerelerde kullanılır?

Eğer “bit manipülasyonu”nun faydalarını elde edemeyeceğiniz bir proje ise, muhtemelen bunları kullanmamalısınız. Tıpki bir çok enterprise uygulama gibi. İyi tarafları hızlı olmaları, kötü(?) tarafları anlaşılabilirliğin düşük olması, kod okunabilirliğini azaltmaları ve maintain edilebilmelerinin zorluğu diyebilirim. Bunun dışında, en küçük bir “performans” kaybı bile sizin için değerli ise, o zaman bunları kullanmayı düşünebilirsiniz. Örnek olarak, C ile driver geliştirirken, en derin seviyede bir matematiksel işlemler yapıyorsanız bunları kullanabilirsiniz. Genel olarak right shift ve left shift operatörleri, çarpma ve bölme işlemlerine göre genellikle hızlı çalışırlar. Tabi günümüz derleyicileri, bunları olabildiğince optimize ediyorlar hali hazırda.

        /// <summary>
        /// Sayını kaç adet bitten oluştuğunu bulur.
        /// </summary>
        static int BitCount(int n)
        {
            var bitCount = 0;

            while((1 << bitCount) <= n)
            {
                bitCount++;
            }

            return bitCount;

            // Örn: n = 5, yani 101, bizim 1 sayısını 3 defa ötelersek 1000
            // değerine, yani 5'ten büyük bir değer görüyoruz.
        }

        /// <summary>
        /// Belirli bir pozisyondaki bit değerini getirir.
        /// </summary>
        static int GetBit(int n, int position)
        {
            return (n >> position) & 1;

            // Ör: 11010 ve position = 3 olsun.
            // Sağa shift ettiğimizde elimizde 11 değeri kalır.
            // Bunu da 1 ile bitwise AND'lediğimizde, 
            // son bit eğer 1 ise 1, değilse 0 döndürür.
        }

        /// <summary>
        /// Sayı çift mi?
        /// </summary>
        static bool IsEven(int n)
        {
            return (n & 1) == 0;
        }

        /// <summary>
        /// Sayı pozitif mi?
        /// </summary>
        static bool IsPositive(int n)
        {
            if(n == 0)
            {
                return false;
            }

            return ((n >> 31) & 1) == 0;

            // 31 adet shift ile most significant bit'i buluruz.
            // Bu bit 0 ise pozitif, değilse negatiftir.
        }

Asal Çarpanları Bulma Algoritması

Bir sayıyı oluşturan asal çarpanların nasıl en efektif şekilde bulunabileceğini anlattım bu videoda. Önemli olan iki nokta var; birincisi kontrol edeceğimiz sayıları verilen sayının kareköküne kadar (karekökü dahil) iterasyon ile kontrol etmek ve elimizdeki sayıyı bölebildiğimiz kadar o sayıya bölmek, ikincisi de eğer bu iterasyon sonrası sayımız 1’e eşit olmadıysa (videoda anlattığım 99 örneği gibi) son kalanı da listeye eklemek.

► Asal çarpan nedir? https://tr.wikipedia.org/wiki/Asal_%C3%A7arpan

Asal çarpan, bir sayının asal olan çarpanlarına denir. Örnek olarak 72 sayısının asal çarpanları 2 ve 3’ken (2^3 * 3^2), 4, 6, 8, 9, 12, 18, 24, 36, 72 asal çarpan değildir. Aritmetiğin temel teoremine göre bütün bileşik sayılar, asal çarpanların çarpımı olarak yazılabilmektedir.

        /// <summary>
        /// Sayının tüm asal çarpanlarını bulma
        /// </summary>
        static IList<int> PrimeFactors(int n)
        {
            var factors = new List<int>();

            for(var i = 2; i <= Math.Sqrt(n); i++)
            {
                while(n % i == 0)
                {
                    n /= i;
                    factors.Add(i);
                }
            }

            if (n != 1)
                factors.Add(n);

            return factors;
        }

LeetCode Çözümleri – 1249. Minimum Remove to Make Valid Parentheses

LeetCode içerisinde bulunan “Minimum Remove to Make Valid Parentheses” sorusunun açıklaması ve çözümü. Bu soruda size verilen bir string içerisinde, en az kaç adet parantez silerek “geçerli” bir string oluşturabileceğiniz soruluyor.

Geçerli bir string’in tanımı olarak;

► Boş string ve sadece küçük harfler içeren, veya

► A ve B geçerli string’ler olup AB şeklinde olan veya

► A geçerli string olup (A) şeklinde olanlardan bahsedilmiş.

► LeetCode 1249. Minimum Remove to Make Valid Parentheses: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/

► Problem açıklaması:

Given a string s of ‘(‘ , ‘)’ and lowercase English characters. Your task is to remove the minimum number of parentheses ( ‘(‘ or ‘)’, in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

It is the empty string, contains only lowercase characters, or

It can be written as AB (A concatenated with B), where A and B are valid strings, or

It can be written as (A), where A is a valid string.

Example 1:

Input: s = “lee(t(c)o)de)”

Output: “lee(t(c)o)de”

Explanation: “lee(t(co)de)” , “lee(t(c)ode)” would also be accepted.

Example 2:

Input: s = “a)b(c)d”

Output: “ab(c)d”

Example 3:

Input: s = “))((”

Output: “”

Explanation: An empty string is also valid.

Example 4:

Input: s = “(a(b(c)d)”

Output: “a(b(c)d)”

Constraints:

1 <= s.length <= 10^5

s[i] is one of ‘(‘ , ‘)’ and lowercase English letters.